Reputation: 1435
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?
Upvotes: 0
Views: 3255
Reputation: 3180
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! :)
Upvotes: 1