Neil N
Neil N

Reputation: 25278

MVC HttpPost attribute not working

For some reason both the Get and Post fire the first action.

public ActionResult Login()
{
   return View();
}

[HttpPost]
public ActionResult Login(FormCollection form)
{
   // Login Stuff here... never gets reached!
}

I've basically copied this directly from the MVC music store sample. Tried it in another app and it worked fine.

this is a fairly new project, used the base MVC3 project template in Visual Studio, all the default settings.

I made sure the HTML output specifies the POST method:

<form action="/Home/Login" method="post">

Here is my Login.cshtml

@{
    ViewBag.PageTitle = "Login";
}
<section id="index">
<header>
    <h2>Login</h2>
</header>
<content>
    @using (Html.BeginForm("Login", "Home", FormMethod.Post))
    {
        <panel id="login">
            <table>
                <tr>
                    <td>Email:</td>
                    <td><input name="Email" /></td>
                </tr>
                <tr>
                    <td>Password:</td>
                    <td><input name="Password" type="password" /></td>
                </tr>
                <tr>
                    <td colspan="2" align="center"><input type="submit" value="Login" /></td>
                </tr>
            </table>
        </panel>
    }
</content>
</section>

After I submit the form I see this URL in my browser:

http://localhost:51606/Home/[email protected]&Password=mypass

Those fields should not be in the URL! Why on earth is my form getting converted to a GET request?

Upvotes: 4

Views: 7864

Answers (2)

Luis Hinojojs
Luis Hinojojs

Reputation: 11

I just added method="post" action="" into form tag and it worked.

@{
    ViewBag.Title = "Add New Entry";
}

<h2>Add New Entry</h2>


<form method="post" action="">  

       <fieldset>

            Please enter your name: <br />
            <input type="text" name="Name" maxlength="200" />
            <br /><br />
            Please enter your message: <br />
            <textarea name="Message" rows="10" cols="40"> </textarea>
             <br /><br />
            <input type="submit" value="Submit Entry" /> 
        </fieldset>
</form>       

Upvotes: 1

Neil N
Neil N

Reputation: 25278

Looking at the HTML output some more, I spotted another form tag surrounding my form.

Turns out someone (me) put a form tag in the Views/Shared/_Layout.cshtml, which is the default shared layout.

bah, figures after typing in the question here I would find the problem.

Upvotes: 4

Related Questions