Asp.net Mvc jquery ajax? - asp.net-mvc

I have links like following.
Deneme Müşteri 2
Deneme Müşteri 2
I want to use jquery ajax post like this:
$(".customer_details").click(function () {
$.ajax({
url: $(this).attr("href"),
type: 'POST',
beforeSend: function () {
},
complete: function () {
},
success: function (result) {
$("#customer_operations_container").html(result);
},
error: function (result) {
alert("Hata!");
}
}); //end ajax
});
Or this:
$(".customer_details").click(function () {
$("#customer_operations_container").load($(this).attr("href"));
});
And Action Method
public ActionResult _EditCustomer(int CustomerId)
{
// get customer from db by customer id.
return PartialView(customer);
}
But I cant do what I wanted. When I click to link, PartialView does not load. It is opening as a new page without its parent. I tried prevent.Default but result is the same.
How can I load the partialView to into a div?
Note: If I use link like this <a href="#"> it works.
Thanks.

Maybe the problem is with the actionresult, try with Content to see if that changes anything.
public ActionResult _EditCustomer(int CustomerId)
{
// get customer from db by customer id.
return Content(customer.ToString());
}
Try one of these...
$(".customer_details").click(function (e) {
e.preventDefault()
$.ajax({
url: $(this).attr("href"),
//I think you want a GET here? Right?
type: 'GET',
beforeSend: function () {
},
complete: function () {
},
success: function (result) {
$("#customer_operations_container").html(result);
},
error: function (result) {
alert("Hata!");
}
}); //end ajax
});
Or
$(".customer_details").click(function (e) {
e.preventDefault();
$("#customer_operations_container").load($(this).attr("href"));
});
Or
$(".customer_details").click(function (e) {
e.preventDefault();
$.get($(this).attr("href"), function(data) {
$("#customer_operations_container").html(data);
});
});
If none of this works, check if there's any js errors

The problem is when you click on the link you already start navigation to it. So just use e.preventDefault() or return false from the click method to prevent the default behavior
$(".customer_details").click(function (e) {
e.preventDefault();
...
}

This should help you out:
$.ajax({
url: $(this).attr("href"),
type: 'POST',
beforeSend: function () {
},
complete: function () {
},
success: function (result) {
$("#customer_operations_container").html(result);
},
error: function (result) {
alert("Hata!");
}
}); //end ajax
return false;
The only thing you where missing is the prevention of A tag working. By returning false your custom event is called and the default event is not executed.

Try this
$(function(){
$(".customer_details").click(function (e) {
e.preventDefault();
});
});
Using ready event
Demo: http://jsfiddle.net/hdqDZ/

Related

#Html.CheckBoxFor onchange actionlink

How can I make the code below an on change actionlink? So when I check the checkbox it will trigger an actionlink!
#Html.CheckBoxFor(c => OutOfBank.Available)
You can send an Ajax request when Checkbox changed, which triggers the action each time you check or uncheck the checkbox.
#Html.CheckBoxFor(c => OutOfBank.Available)
<script>
$(function () {
$('#Available').change(function () {
$.ajax({
url: '/example/#OutOfBank.Available',
cache: false,
method: 'GET',
success: function (data) { alert('success'); },
error: function () { alert('error'); }
});
});
});
</script>

How to use ajax in mvc?

I am a very beginner to mvc and ajax both.
I have tried many examples on net but I don't understand how ajax is used practically?
I have a controller named members which has GetAllMembers Method.
GetAllMembers returns a List<Members>
Now I want to use JQuery and ajax something like :
$(document).click(function () {
$.ajax({
url: "Members/GetAllMembers",
success: function () {
},
error: function () {
alert("Failed to get the members");
}
});
});
Is my URL right?
Upon success I want to display that List in a ListBox.
How can I get it? Can anyone give me a start?
$.ajax({
type: "POST",
url: "Members/GetAllMembers", //Your required php page
data: "id="+ data, //pass your required data here
success: function(response){ //You obtain the response that you echo from your controller
$('#Listbox').html(response); //The response is being printed inside the Listbox div that should have in your html page.
},
error: function () {
alert("Failed to get the members");
}
});
Hope this will help you.. :)
$(document).click(function () {
$.ajax({
url: "Members/GetAllMembers",
success: function (result) {
// do your code here
},
error: function () {
alert("Failed to get the members");
}
});
});
So your request give response in "result" variable. So you have to easily manage result variable value in foreach loop and set value in ListBox HTML.
Follow this example:
suppose you have this html:
<p>List Box - Single Select<br>
<select id="listBox" name="listbox">
</select>
</p>
So we have this js:
var template = '<option value="$value">$name</option>';
var getAllMembers = function() {
$.ajax({
url: 'Members/GetAllMembers',
dataType: 'json', //Assuming Members/GetAllMembers returns a json
success: function(response) {
$.each(response, function(index){
var option = template.replace(/\$value/g, this.value)
.replace(/\$name/g, this.name);
$('#listBox').append(option);
});
}
});
};
EDIT: Now you only need to call getAllMembers(); function.
Hope this help.
Pablo.

Dynamically added form ajax not work

I have a list of div's.
When I click on a button in a div I switch div content with partial view which contain form.
This is code that happens when I click on that button:
#Html.ActionLink("edit", "EditUserLanguage", "UserLanguage", new { userLanguageId = Model.UserLanguageId }, new { #class = "editButton" })
...
$(document).on('click', '.editButton', function (e) {
$.ajax({
url: this.href,
cache: false,
success: function (html) {
var id = $(e.target).closest("div").attr("id");
$("#" + id).empty();
$("#" + id).append(html);
}
});
return false;
});
Html (partial view) that I add has:
#using (Html.BeginForm("UpdateUserLanguage", "UserLanguage", FormMethod.Post, new { id = "updateUserLanagegeForm" }))
{
...
This main view where is the list of div's and where I add this new partial view I have this code:
$(function () {
$('#updateUserLanagegeForm').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
alert("work");
}
});
return false;
});
}); //update
When I click on submit action method is invoked and I get new partial view returned but not via ajax.
I only get that partial view returned. alert("work"); is never called.
What could be the reason that this ajax call doesn't work?
submit handler is not being attached to form as form gets loaded after dom ready. So change your code to -
$('body').on('submit','#updateUserLanagegeForm',(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
alert("work");
}
});
return false;
});
This will attach handler to form even if it is added dynamically.

Jquery Ajax post animation during ajax process?

I do ajax post on my mvc app when dropdown change.
$(function () {
$('#meters').change(function () {
var analizor_id = $(this).val();
if (analizor_id && analizor_id != '') {
$.ajax({
url: '#Url.Action("AnalizorInfoPartial", "Enerji")',
type: 'GET',
cache: false,
data: { analizor_id: analizor_id },
success: function (result) {
$('#TableAnalizorInfo').html(result);
}
});
}
});
});
DropDown
#Html.DropDownList("sno", new SelectList(Model, "sno", "AnalizorAdi"), "-- Analizör Seçiniz --", new { id = "meters" })
Can I show a loading image or anything else during ajax process? (between begin - finish event) and Code example?
EDIT
Can I use like this?
success: function (result) {
$('#TableAnalizorInfo').html(result);
}
begin:function(){
//show image
}
complete:function(){
//hide image
}
Thanks.
Of course, the events you are looking for are beforeSend and complete:
if (analizor_id && analizor_id != '') {
$.ajax({
url: '#Url.Action("AnalizorInfoPartial", "Enerji")',
type: 'GET',
cache: false,
beforeSend: function() {
// Show your spinner
},
complete: function() {
// Hide your spinner
},
data: { analizor_id: analizor_id },
success: function (result) {
$('#TableAnalizorInfo').html(result);
}
});
}
or you could do it globally for all AJAX requests on the page using global AJAX event handlers:
$(document).ajaxSend(function() {
// Show your spinner
}).ajaxComplete(function() {
// Hide your spinner
});

how to redirect to a view on $.AJAX complete - asp.net mvc 3

Ok..i want to redirect a user after the validation check using $.AJAX to a peritcular view... how do i do that ? .. pleae help...
here is my $.AJAX code... EX: i want user redirected to "/Home/Movies" controller action...
if not logged in stay on the same page...
<script type="text/javascript">
$('#btnLogin').click(function () {
var email = $('#Email').val();
var Password = $('#Password').val();
var postdata =
{
"Email": email,
"Password": Password
};
$('.Loading').fadeIn(50);
$.ajax({
url: '#Url.Action("CheckLogin","Home")',
data: postdata,
success: function (msg) {
var data = msg.split(':');
$('#Result').html(data[0]);
$('.Loading').fadeOut(50);
},
error: function (data) {
$('#Result').html(data);
$('.Loading').fadeOut(50);
}
});
});
</script>
here is my controller action which is used for checking Login details...
public ContentResult CheckLogin(Users checkuser)
{
if (db.CheckUserLoginDetails(checkuser.Email, checkuser.Password))
{
return Content("Login Successful:" + checkuser.Email);
}
else
{
return Content("Login UnSuccessful");
}
}
also how can i pass a returned results from this view to another view.. in this exmaple if the user is logged in i want to show his email id on the redirected page which is lets say "/home/Movies"
thx in advance
Show your loading image before ajax request, and hide on success or error handlers.
add <div class="loading">Loading...</div> to your markup
$('.loading').fadeIn(50);
$.ajax({
url: '#Url.Action("CheckLogin","Home")',
data: postdata,
success: function (msg) {
$('#Result').html(msg);
$('.loading').fadeOut(50);
},
error: function (data) {
$('#Result').html(msg);
$('.loading').fadeOut(50);
}
});
Take a look at the ajaxStart() and ajaxStop() event handlers in jQuery. You could use these to show and hide a layer with a gif-animation.
http://api.jquery.com/ajaxStart/
http://api.jquery.com/ajaxStop/
use beforSend and complete attributes.
$.ajax({
url: '#Url.Action("CheckLogin","Home")',
data: postdata,
success: function (msg) {
$('#Result').html(msg);
},
error: function (data) {
$('#Result').html(msg);
},
beforeSend: function() {
$("body").append("<div class=\"ajaxLoader\" id=\"ajaxLoader"\"><div class=\"ajaxAnimation\"></div></div>");
$("#ajaxLoader").hide();
$("#ajaxLoader").fadeIn('fast');
},
complete: function() {
$("#ajaxLoader").remove();
}
});
And specify animation with css
.ajaxAnimation {
background-image: url('images/ajax-loader.gif');
background-repeat: no-repeat;
background-position: center center;
}

Resources