In ASP.NET MVC: All possible ways to call Controller Action Method from a Razor View
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; }}
Method 2 : Using jQuery Ajax Post call (partial page update).
Suitable for when you need to do partial page post data into database.
Post method is also same like above just replace [HttpPost]
on Action method and type as post
for jquery method.
For more information check Posting JSON Data to MVC Controllers Here
Method 3 : As a Form post scenario (full page update).
Suitable for when you need to save or update data into database.
View
@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post)){ @Html.TextBoxFor(model => m.Text) <input type="submit" value="Save" />}
Action Method
[HttpPost]public ActionResult SaveData(FormCollection form) { // Get movie to update return View(); }
Method 4 : As a Form Get scenario (full page update).
Suitable for when you need to Get data from database
Get method also same like above just replace [HttpGet]
on Action method and FormMethod.Get
for View's form method.
I hope this will help to you.