[英]How to check null object in razor view editor template
在我的ViewModel中,我創建了一個Object類型的屬性,並從控制器中傳遞了該對象類型屬性的值。 現在,我已經創建了一個編輯器模板來處理該對象類型。 這是我的代碼:
<div class="form-group">
@Html.EditorFor(x => Model.testProp)
</div>
基於值類型,此編輯器模板正在調用不同類型的編輯器模板(String,Date,int)。 現在如何使用編輯器模板處理null / empty字符串? 如果我的Model.testProp為null,那么如何調用返回空TextField的編輯器模板?
您是否嘗試過進行null
檢查並基於此選擇要使用的模板?
像這樣:
<div class="form-group">
@if (Model.testProp != null)
{
// If not null; Use the correct template, based on the type
@Html.EditorFor(x => x.testProp)
}
else
{
// Otherwise print an empty text box
@Html.TextBoxFor(x => x.testProp)
}
</div>
您還可以在if
語句中使用!string.IsNullOrWhiteSpace(Model.testProp)
來檢查空白string
s。
這樣一來,當testProp
為 null
,一個<input type="text"...>
將被創建,使用正確的字段名稱時您匹配POST
一些值回控制器。
另外,我不知道它是否有任何區別,但是我通常將謂詞表達式聲明為x => x.testProp
我在上面的示例中使用了它。
希望這可以幫助! :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.