2011-06-07 69 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>