简体   繁体   English

如何在razor视图编辑器模板中检查空对象

[英]How to check null object in razor view editor template

In my ViewModel I have created a property of type Object and from controller I am passing a value of that object type property. 在我的ViewModel中,我创建了一个Object类型的属性,并从控制器中传递了该对象类型属性的值。 Now I have created a Editor template to handle that Object type. 现在,我已经创建了一个编辑器模板来处理该对象类型。 Here is my code for that: 这是我的代码:

   <div class="form-group">
         @Html.EditorFor(x => Model.testProp)
   </div>

Based on the value type this editor template is calling different types of editor templates(String,Date, int). 基于值类型,此编辑器模板正在调用不同类型的编辑器模板(String,Date,int)。 Now how can I handle null/empty string using editor template? 现在如何使用编辑器模板处理null / empty字符串? If my Model.testProp is null then how can I call the editor template which returns empty TextField? 如果我的Model.testProp为null,那么如何调用返回空TextField的编辑器模板?

Have you tried doing a null check and choosing which template to use, based on that? 您是否尝试过进行null检查并基于此选择要使用的模板?

Like this: 像这样:

<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>

You can also use !string.IsNullOrWhiteSpace(Model.testProp) in your if statement, to check against blank string s. 您还可以在if语句中使用!string.IsNullOrWhiteSpace(Model.testProp)来检查空白string s。

This way, when the testProp is null , an <input type="text"...> will be created, with the correct field name to match when you POST some values back to the controller. 这样一来,当testProp null ,一个<input type="text"...>将被创建,使用正确的字段名称时您匹配POST一些值回控制器。

Also, I don't know if it makes any difference, but I usually declare the predicate expression as x => x.testProp - I've used this in my sample above. 另外,我不知道它是否有任何区别,但是我通常将谓词表达式声明为x => x.testProp我在上面的示例中使用了它。

Hope this helps! 希望这可以帮助! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM