![](/img/trans.png)
[英]Does a model need to be explicitly passed to a view if the model is strongly bound to the view?
[英]View Model Null when not explicitly passed by controller to strongly typed view
我的觀點是定義的
@model BloombergGUI.Models.SecurityViewAltModel
<div class="col-md-10">
@Html.TextArea("TestArea",Model.FieldsList)
@Html.TextAreaFor(m => m.FieldsList, new {@class = "form-control"})
</div>
如果此強類型視圖的控制器定義為
public ActionResult Index()
{
return View(); //The first Html.TextArea says Model.FieldList is null
}
如果它被定義為以下,則視圖中的兩個語句都有效。
public ActionResult Index()
{
return View(new SecurityViewAltModel());
}
為什么當強類型視圖時,Model.Property指示Model為null但是當我顯式傳遞一個新模型()時,Model.Property工作正常。 我認為Model只是訪問視圖的強類型模型的另一種方式,m => m.property是用於強類型視圖的TextBoxFor擴展方法的lambda表達式。
該
@model BloombergGUI.Models.SecurityViewAltModel
您在View中定義實際上是來自控制器的強類型數據傳遞機制。
當你這樣做
return View();
你應該得到一個NULL模型。 這是因為沒有數據傳遞給View。 模型預計為空。
當你這樣做
return View(new SecurityViewAltModel());
發送非null Model對象,所有字段為null。 MVC將為這些空數據字段呈現空控件。
請注意 ,在第二種情況下,您可能無法獲得Null引用異常,因為您沒有處理直接的object.field引用,而是處理Expression 。
m => m.FieldsList
與Model.FieldsList
細節:
在MVC DLL內部,當處理Expression時,它具有如下邏輯:
使用Parameter評估表達式的值作為viewData.Model對象。
電話如下:
CachedExpressionCompiler.Process<TParameter, TValue>(expression)(model);
在那時,它進入FingerprintingExpressionVisitor並且它可以處理null Model並返回null響應以使Extension Helper不呈現任何數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.