Wednesday, June 5, 2013

How to properly submit an html form to MVC Action with model binding

Just like a view can submit data to an MVC action so can any external HTML forms and model binding can even be used allow for greater code re-usability of existing actions. This is helpful, for example, when you have a couple other sites that you would like to link back to your MVC site to take advantage existing functionality.

If you are familiar with MVC, you are probably already thinking this makes sense because views are just html. Even the helpers that are used in Razor or other syntax implementation, ultimately render as plain old html. So what are the gotchas and things to watch out for?

There are only a couple things that are extremely important and most of it has to do with the HTML form itself, and not so much on the controller action side of things.

First and most importantly the form must be configured to submit to the proper place and the correct method is being used.  When using the default routing configuration in MVC this would be the url/controller/action so something like http://www.mysite.com/mycontroller/myaction. Also make sure that if the action is decorated with the HttpPost attribute then set the method to "post" and likewise HttpGet attribute would be a form method of "get"

Now that the form will successfully submit to the proper action it is time to look at the input or select tags and make sure they have the proper id and name attributes.  I put the word "and" in bold because the model does not bind correctly if you do not have these both properly defined.  To define these properly make sure both the id and name attributes match the name of the parameter of the action or one of the property names of the model being used as the action parameter. For example if myAction had a parameter name "testParam" and "testParam2" then I would need two inputs with the id and name matching the "testParam" for one and "testParam2" for the other.

Example Form:
<form action="http://mycorrecturl/mycontroller/myaction" method="post">
<input id="testParam" name="testParam" type="text" />
<input id="testParam2" name="textParam2" type="hidden" value="junk" />
<input type="submit" title="Submit" />
</form>


Example Action
[HttpPost]
public ActionResult myAction(string testParam, string testParam2)
{
     //do something here
     return View();
}


There are other concerns that require time invested into understanding with MVC in general, like proper request filtering, authentication and other security concerns to ensure that your site and users are safeguarded. For more information about these topics I recommend reviewing Microsoft's MVC tutorial library at http://www.asp.net/mvc/tutorials as a good starting point.    

No comments:

Post a Comment