Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In ASP.NET MVC: All possible ways to call Controller Action Method from a Razor View

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.

like image 822
dan Avatar asked Dec 27 '12 05:12

dan


People also ask

How do you call a controller method from Razor view?

We can use @html. action to call controller method.

How many types of action methods are there in MVC?

There are two methods in Action Result. One is ActionResult() and another one is ExecuteResult().


1 Answers

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.

like image 147
Sampath Avatar answered Oct 06 '22 05:10

Sampath