2011-06-07 70 views
4

由于某些原因,Get和Post都会触发第一个操作。MVC HttpPost属性不起作用

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

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

我已经基本上从MVC音乐商店示例中直接复制这个。尝试在另一个应用程序,它运行良好。

这是一个相当新的项目,在Visual Studio中使用了基本的MVC3项目模板,所有的默认设置。

我确定HTML输出指定POST方法:

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

这里是我的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> 

后,我提出我看到这个网址在浏览器形式:

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

这些字段不应该在URL中!为什么我的表单转换为GET请求?

+2

我复制了你的代码,但它对我来说工作得很好。对不起,我甚至不知道该怎么建议!也许......确保使用正确的视图? – Beno 2011-06-07 04:09:05

+0

@Beno:请参阅下面的答案。我应该首先查看整个HTML输出。 – 2011-06-07 04:27:59

回答

4

再看看HTML输出,我发现了另一个表单标签,它围绕着我的表单。

结果有人(我)在Views/Shared/_Layout.cshtml中放置了一个窗体标签,这是默认的共享布局。

唉,在这里输入问题后的数字我会发现问题。

1

我刚添加method =“post”action =“”到表单标签中,它就起作用了。

@{ 
    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>