Asp.Net MVC – handling multiple submit from a view

In Asp.Net MVC, after understanding of how controller communicates with Views, the biggest challenge i found was to handle multiple form submit requests. Almost every view will have multiple buttons to post/submit data (ideally a ViewModel) to controller. In this post I am assuming that you are comfortable with very basics of MVC.

To do this sample just create a Asp.Net MVC web application project and write the code in “Views/Index.cshtml” at the end because by default this is the landing page of default website template.

This code is just a sample which may not be practical in real world scenario.

@using (Html.BeginForm("MyCommonSubmitAction", "Home", FormMethod.Post)) {

<input type ="text" id="txtComments"  /> <br />

<input type="submit" name="approve" id="btnApprove" value="Approve"/>
<input type="submit" name="reject" id="btnReject" value="Reject" />
}

Now, Let us see the controller action method how it will differentiate these two submits.

[HttpPost]
public ActionResult MyCommonSubmitAction(FormCollection frm)
{
var button = frm["approve"] ?? frm["reject"];
//var comments  =  frm["txtComments"]; assuming view is not strongly typed
switch (button )
{
case "Approve" :
// do your thing
break;

case "Reject"  :
// do your thing
break;

default:
return View("Index");
}

return View("Index");

}

Now, this is just one of the ways you can differentiate multiple submit requests. Important thing to notice here is that FormCollection
is bound to the post request and is available as a parameter which actually holds all the form fields posted to the controller. Ideally every view should be bound to a strongly type ViewModel.

There are better ways of binding your data model to your view. Those who are new to Asp.Net MVC. I would recommend you to read Scott Gu post on model binding.

Advertisements

About saxenapraveen

I work with Microsoft and have 12 years of experience in developing,designing and leading reliable and scalable solutions for cloud and device ready businesses.

Posted on August 14, 2012, in .NET, ASP.NET MVC and tagged , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: