2012-02-23 41 views
3

在場景下方,我想我必須在第一次加載時看到表單中的START文本。 當我點擊發送數據按鈕並提交時,我等待在我的表單中看到完成文本。MVC3 Form Posted Value

買的時候我按一下按鈕,併發布形式中,啓動文本永遠不會改變......

任何人都可以告訴這個問題?

我的控制器:

namespace MvcApplication1.Controllers 
{ 
    public class BuyController : Controller 
    { 
     public ActionResult Index(BuyModel model) 
     { 
      if (Request.HttpMethod == "GET") 
      { 
       model.Message= "START"; 
       return View(model); 
      } 
      else 
      { 
       BuyModel newModel = new BuyModel(); 
       newModel.Message= "FINISH"; 
        return View(newModel); 
      } 
     } 
    } 
} 

我的觀點:

@model MvcApplication1.Models.BuyModel 
@using (Html.BeginForm("Index", "Buy", FormMethod.Post)) 
{ 
     @Html.TextBoxFor(s => s.Message) 
    <button type="submit" >Send</button> 
}    

我的模型:

public class BuyModel 
{ 
    public string Message { get; set; } 
} 

回答

4
  public class BuyController : Controller 
      { 
       public ActionResult Index() 
       { 
        BuyModel model = new BuyModel(); 
        model.Message= "START"; 
        return View(model); 
       } 

       [HttpPost] 
       public ActionResult Index(BuyModel model) 
       { 
        model = new BuyModel(); 
        model.Message= "FINISH"; 

        ModelState.Clear(); // the fix 

        return View(model); 
       } 
      } 

查看:

@model MvcApplication1.Models.BuyModel 
@using (Html.BeginForm("Index", "Buy")) 
{ 
     @Html.TextBoxFor(s => s.Message) 
    <button type="submit" >Send</button> 
} 

您的問題是因爲您的原始代碼,該Action方法將僅作爲HTTP GET請求執行。 ASP.NET MVC允許您指定具有[HttpPost]屬性的帖子(請參閱上面的代碼)。

我不確定您在POST期望的行爲中獲得了什麼。看起來好像你只是抹去POST上推送的任何表單值。所以相應地修改我的上面的代碼,但它應該給你一般的想法。

編輯:它似乎是文本框在POST後保留其值。這不僅僅是"START",但如果您在該文本框中輸入任何內容並點擊提交,那麼您在提交表單時就會在文本框中顯示完全相同的文本。

編輯編輯:查看更改後的代碼。請在您的POST操作方法中撥打ModelState.Clear(),您將得到正確的值。

+0

感謝您的回覆,但您的代碼與我的代碼完全相同。 [HttpPost]屬性做我在我的代碼中做的事情... 它具有相同的效果... – AltugCan 2012-02-23 19:46:27

+0

@AltugCan好吧,我明白你在說什麼了。如果你用一個'LabelFor()'代替文本框,它會按照你的想法工作。但由於某種原因,文本框的值正在被覆蓋。如果您仔細查看代碼,您會看到在POST操作中設置了正確的模型數據。望着它... – 2012-02-23 20:08:52

+0

@AltugCan,雅,但一般來說,你不應該爲http動詞寫mvc應用程序。這些屬性是有原因的,並有助於代碼可讀性(加上更多) – 2012-02-23 20:11:54

1

如果您發佈,並且不返回RedirectResult,默認情況下,助手將使用ModelState中的值。您需要清除ModelState或使用其他方法。

MVC中的PRG(post重定向get)模式非常重要。因此,如果它是一個帖子,並且您沒有重定向,那麼助手會認爲有一個錯誤需要糾正,並從ModelState中提取值。

相關問題