I know this is a pretty basic question over here.
But could you tell me all possible options available to,
call a Control Action Method [generally any server side routine] from a Razor View and,
in what scenarios each are best applicable to be used in.
Thanks.
We can use @html. action to call controller method.
There are two methods in Action Result. One is ActionResult() and another one is ExecuteResult().
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With