![](/img/trans.png)
[英]Why does the ASP.Net MVC model binder bind an empty JSON array to null?
[英]Why does the model binder need an empty constructor
我需要一些基本面的幫助......
我有這個控制器,用一個類的實例來提供我的視圖(至少我認為它是如何工作的)。 因為我給我的視圖一個新的對象實例,為什么它必須為我的帖子創建一個更新的模型綁定? 請看下面的例子。
[HttpGet]
public ActionResult Index(){
int hi = 5;
string temp = "yo";
MyModel foo = new MyModel(hi, temp);
return View(foo);
}
[HttpPost]
public ActionResult Index(MyModel foo){
MyModel poo = foo;
if(poo.someString == laaaa)
return RedirctToAction("End", "EndCntrl", poo);
else
throw new Exception();
}
View:
@model myApp.models.MyModel
@html.EditorFor(m => m.hi)
<input type="submit" value="hit"/>
Model:
public class MyModel {
public int hi {get; set;}
public string someString {get; set;}
public stuff(int number, string laaaa){
NumberforClass = number;
someString = laaaa;
}
}
為什么我需要一個空白構造函數? 此外,如果我有一個無參數構造函數,為什么poo.someString
會在我進入RedirctToAction("End", "EndCntrl", poo)
?
為什么我需要一個空白構造函數?
因為
[HttpPost]
public ActionResult Index(MyModel foo){ ... }
您要求綁定器在Post上為您提供一個具體實例,因此綁定器需要為您創建該對象。 您的原始對象不會在GET和POST操作之間保留,只有(某些)其屬性作為HTML字段存在。 這就是“HTTP無國籍”的含義。
當你使用較低級別時,它會變得更加明顯
[HttpPost]
public ActionResult Index(FormCollection collection)
{
var Foo = new MyModel();
// load the properties from the FormCollection yourself
}
為什么poo.someString會在我進入
RedirctToAction("End", "EndCntrl", poo)
?
因為您的視圖中未使用someString
。 因此,當您獲得新模型時,它將永遠是空白的。 改變這種情況:
@model myApp.models.MyModel
@html.HiddenFor(m => m.SomeString)
@html.EditorFor(m => m.hi)
<input type="submit" value="hit"/>
這會將值存儲為HTML中的隱藏字段,並在POST時為您恢復。
您傳遞給視圖的模型與您在請求中收到的模型之間沒有直接連接。 在最終的情況下,初始請求和響應的代碼將在IIS的不同實例或甚至不同的機器上運行。
因此,當請求返回時,ASP.Net MVC需要重新創建所有對象(控制器,模型,...)。 使用默認構造函數允許運行時創建新對象,而無需了解自定義構造函數的特定參數。
旁注:對於泛型,存在類似的構造函數重構,其中您只能指定默認構造函數的where T:new()
。
我對這個問題感到有點困惑,但你試過這個:
[HttpPost]
public ActionResult Index(MyModel foo){
if(foo.someString == "laaaa")
return RedirctToAction("End", "EndCntrl", foo);
else
throw new Exception();
}
如果添加了參數化構造函數,則只需要無參數構造函數。
例如:MyObject item = new MyObject();
只要不定義任何構造函數,它就不需要參數較少的構造函數。 如果使用參數定義構造函數,則需要一個參數less constructor,因為它是模型綁定器使用的構造函數。
當您回發值時,活頁夾將您的請求映射到類型化對象,它首先創建對象,然后嘗試將您發布的值映射到某個屬性。
如果你沒有參數較少的構造函數...如果代碼不在你的控制之下,那么你必須創建一個自定義綁定器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.