Friday, March 17, 2017

AJAX Controller Action Method from a Razor View


Issue

How to call to a controller action from jquery?

Method 1 : Using jQuery Ajax Get call (partial page update).
Suitable for when you need to retrieve jSon data from database.
Controller's Action Method
[HttpGet]
public ActionResult Foo(string id)
{
    var person = Something.GetPersonByID(id);
    return Json(person, JsonRequestBehavior.AllowGet);
}
Jquery GET
function getPerson(id) {
    $.ajax({
        url: '@Url.Action("Foo", "SomeController")',
        type: 'GET',
        dataType: 'json',
        // we set cache: false because GET requests are often cached by browsers
        // IE is particularly aggressive in that respect
        cache: false,
        data: { id: id },
        success: function(person) {
            $('#FirstName').val(person.FirstName);
            $('#LastName').val(person.LastName);
        }
    });
}
Person class
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
Key to note here is that the data line id must match the name of the variable in the Action result parameter list.

Source

http://stackoverflow.com/questions/14049817/in-asp-net-mvc-all-possible-ways-to-call-controller-action-method-from-a-razor
http://stackoverflow.com/questions/1194104/jquery-ajax-ajax-passing-parameters-to-callback-good-pattern-to-use
http://stackoverflow.com/questions/15576548/how-to-pass-parameters-in-get-requests-with-jquery

No comments:

Post a Comment