2013-12-19 40 views
0

我在我的視圖中具有以下形式。MVC4發佈表單不能調用控制器方法

@using (Html.BeginForm("PostComment", "Blog")) name) 
    { 
     <fieldset id="frmTester"> 
      <div class="formContainer">  
       <span><input id="username" name="username" /></span>     
       <input id="submit" name="submit" type="submit" value="Submit" /> 
      </div> 
     </fieldset> 
    } 

現在我有下面的方法在我BlogController ...

public ActionResult PostComment(string username) 
    { 

     return View(); 
    } 

我真的不明白MVC很好。我不明白爲什麼我不能得到上面的ActionResult方法來執行。我只是想處理回傳。任何人都有任何想法,爲什麼這不起作用或替代方法。

+3

刪除'名稱)''Blog'之後'))''。 – James

+0

還要在您的輸入中添加適當的類型:'' –

回答

4

使用[HttpPost]:

[HttpPost] 
public ActionResult PostComment(string username) 
{ 
    string u = Request.Form["username"] ; 
    // return Content(u); //if you want dispaly username use this 
    return View(); 
} 
+0

以上都不是。我的視圖被稱爲BlogPost,它已經有一個與它相關聯的ActionResult,就像這樣調用...''''''''''''''返回View(_repository);當我點擊提交按鈕時,即使我沒有調用它,上面的ActionResult也會執行。 – user3036965

+0

我的問題是,當我來自asp.net背景時,.NET中的MVC4如何工作。我想最好的方式來描述它。視圖與Controller方法是否有1對1的關係?任何人都可以請指教? – user3036965

4

更改視圖代碼,這個...

@using (Html.BeginForm("PostComment", "Blog", FormMethod.Post)) 
{ 
    <fieldset id="frmTester"> 
     <div class="formContainer">  
      <span><input id="username" name="username" type="text" /></span>     
      <input id="submit" name="submit" type="submit" value="Submit" /> 
     </div> 
    </fieldset> 
} 

和動作方法來....

[HttpPost] 
public ActionResult PostComment(string username) 
{ 

    return View(); 
}