asp.net-mvchtmlasp.net-mvc-4razor

How to link HTML5 form action to Controller ActionResult method in ASP.NET MVC 4


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();
}

Solution

  • you make the use of the HTML Helper and have

        @using(Html.BeginForm())
        {
            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"/>
        }
    

    or use the Url helper

    <form method="post" action="@Url.Action("MyAction", "MyController")" >
    

    Html.BeginForm has several (13) overrides where you can specify more information, for example, a normal use when uploading files is using:

    @using(Html.BeginForm("myaction", "mycontroller", FormMethod.Post, new {enctype = "multipart/form-data"}))
    {
        < ... >
    }
    

    If you don't specify any arguments, the Html.BeginForm() will create a POST form that points to your current controller and current action. As an example, let's say you have a controller called Posts and an action called Delete

    public ActionResult Delete(int id)
    {
       var model = db.GetPostById(id);
       return View(model);
    }
    
    [HttpPost]
    public ActionResult Delete(int id)
    {
        var model = db.GetPostById(id);
        if(model != null) 
            db.DeletePost(id);
    
        return RedirectToView("Index");
    }
    

    and your html page would be something like:

    <h2>Are you sure you want to delete?</h2>
    <p>The Post named <strong>@Model.Title</strong> will be deleted.</p>
    
    @using(Html.BeginForm())
    {
        <input type="submit" class="btn btn-danger" value="Delete Post"/>
        <text>or</text>
        @Url.ActionLink("go to list", "Index")
    }