MVC-Action Selectors

Action Selectors HttpGet and HttpPost

Action Selectors

When the MVC Framework is selecting one of the controller public methods to invoke as an action, it will use any action selector attribute that might be present to define the correct action to invoke.

1. ActionName

2. AcceptVerbs

  • HttpPost
  • HttpGet

ActionName: When we apply this to a controller action it will specify the action name for that method. For the Index method we have bellow we no longer reach this method as action name “Index”. We have to reach this method as “Start”. (http://localhost:123/Home/Start)

[ActionName(“Start”)]
public ActionResult Index()
{
ViewBag.Message = “Welcome to Deccansoft!”;
return View();
}
Note: A view by name “Start” must be added. Index view will not work.

*Can be used if the URL has “_” or “-“ and method doesn’t have the same.

*Also useful when method names and parameters are same for both HTTPGet and HTTPPost.

Also
[ActionName(“GetCSVFileContent”)]

public ActionResult GetCSV()
{
string csv = CreateCSV();
return new ContentResult() { Content = csv, ContentEncoding =
System.Text.Encoding.UTF8, ContentType = “text/csv” };
}

AcceptVerbs: Http verbs allow us to reach a particular action we can say action method is reachable with:

1. [HttpGet] or [AcceptVerbs(HttpVerbs.Get)]

2. [HttpPost] or [AcceptVerbs(HttpVerbs.Post)]

3. [RequireHttps] – Forces the Http request to be resent over Https.

HttpGet: Only get request will be served by action method.

[HttpGet]
public ActionResult LogOn()
{
return View();
}

HttpPost: Only post request will be served by the action method.

In View: @{ Html.BeginForm(); }

<input type=”submit” value=”Submit” /> @{ Html.EndForm(); }

In Controller:

[HttpPost()]

public ActionResult Index(FormCollection col)

{
ViewBag.Greetings1 = “Posted”;
return View();
}

 


Learn Complete ASP.NET MVC 5.2

Leave a Reply