2013-02-01 73 views
1

我的問題是關於綁定在MVC中。你能幫我一下嗎?綁定在ASP.NET MVC

我的控制器:

public class TestController : Controller 
{ 
     // 
     // GET: /Test/ 
     [HttpGet] 
     public ActionResult Index() 
     { 
      return View(new TestModel()); 
     } 
     public ActionResult Index(TestModel test) 
     { 
      return View(test); 
     } 
} 

筆者認爲:

@model MvcApplication1.Models.TestModel 

@using (Html.BeginForm()) 
{ 
@Html.TextBoxFor(x => x.test) // or x.Test 
<input type="submit" value="Set"/> 
} 

我的模型:

public class TestModel 
{ 
public string test { get; set; } // or Test{get;set;} 
} 

問題是在控制器參數的 「測試」 的名字連爲我理解。我剛將它改爲「模型」並且綁定正在工作。但它在原始狀態下不工作(參數的名稱是'test'),'test'參數爲空。

請給我理解爲什麼綁定在當前示例中不起作用。萬分感謝!

+1

模型中測試參數的值爲空,因爲它從不被設置爲任何值。 –

+0

我不明白 - 爲什麼。我的帖子正文有test = value。首先,活頁夾在帖子主體(以及其他一些地方)中搜索'test.test'。之後它應該搜索簡單的'測試'並且與模型綁定。對 ?或者,我認爲錯誤的綁定過程.. – Udgin

回答

0

您需要在第二種方法中使用[HttpPost]屬性。您也不能使用test作爲您的變量名稱,因爲它與您嘗試綁定到的類的屬性名稱相同; ModelBinder無法確定使用哪個。您的代碼如下所示:

public class TestController : Controller 
{ 
     // 
     // GET: /Test/ 
     [HttpGet] 
     public ActionResult Index() 
     { 
      return View(new TestModel()); 
     } 

     // 
     // POST: /Test/ 
     [HttpPost] 
     public ActionResult Index(TestModel testModel) 
     { 
      return View(testModel); 
     } 
} 
+0

它不工作。操作中的測試變量「Index(TestModel test)」爲空。默認綁定仍然不起作用。 – Udgin

+0

你是否在做任何修改ModelBindingContext的事情? – doctorless

+0

不,它只是我添加到Empty MVC4 New項目的代碼。我添加了這些控制器,視圖和模型,沒有別的。也許這是一些默認綁定的具體實現,我不知道。 – Udgin