MVC HttpPost attribute not working

非 Y 不嫁゛ 提交于 2019-12-22 08:28:58

问题


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/Login?Email=me@email.com&Password=mypass

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


回答1:


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.




回答2:


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>       


来源:https://stackoverflow.com/questions/6260394/mvc-httppost-attribute-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!