简体   繁体   中英

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. 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). Now how can I handle null/empty string using editor template? If my Model.testProp is null then how can I call the editor template which returns empty TextField?

Have you tried doing a null check and choosing which template to use, based on that?

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.

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.

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.

Hope this helps! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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