I have a basic form for which I want to handle buttons inside the form by calling the ActionResult
method in the View's associated Controller
class. Here is the following HTML5 code for the form:
<h2>Welcome</h2>
<div>
<h3>Login</h3>
<form method="post" action= <!-- what goes here --> >
Username: <input type="text" name="username" /> <br />
Password: <input type="text" name="password" /> <br />
<input type="submit" value="Login">
<input type="submit" value="Create Account"/>
</form>
</div>
<!-- more code ... -->
The corresponding Controller
code is the following:
[HttpPost]
public ActionResult MyAction(string input, FormCollection collection)
{
switch (input)
{
case "Login":
// do some stuff...
break;
case "Create Account"
// do some other stuff...
break;
}
return View();
}
Here I'm basically wrapping a button in a link. The advantage is that you can post to different action methods in the same form.
Adding parameters:
Adding parameters from a non-enumerated Model:
You can do the same for an enumerated Model too. You would just have to reference a single entity first. Happy Coding!
you make the use of the HTML Helper and have
or use the Url helper
Html.BeginForm
has several (13) overrides where you can specify more information, for example, a normal use when uploading files is using:If you don't specify any arguments, the
Html.BeginForm()
will create aPOST
form that points to your current controller and current action. As an example, let's say you have a controller calledPosts
and an action calledDelete
and your html page would be something like: