stovroz
stovroz

Reputation: 7065

How do you access the model in an EditorFor template?

How do you access the model in an ASP.NET MVC Editor Template? For example if the parent view contains say:

@Html.EditorFor(x => x.Surname)

Then inside Views/Shared/EditorTemplates/String.cshtml we have:

@model String

<div class="field">
    @Html.LabelFor(x => x)
    @Html.TextBoxFor(x => x)
    @Model.Length
</div>

This fails at @Model.Length because Model is null, although the LabelFor and TextBoxFor render the correct Surname properties.

When Html.DisplayFor with the equivalent template file is used, Model does contain the given string value.

Upvotes: 0

Views: 637

Answers (1)

DLeh
DLeh

Reputation: 24395

Creating a Editor Template for something as broad as String could have unintended consequences, since you will very likely have many EditorFor(x => x.StringValue)s in your code that you don't want this Editor Template to apply to.

It's likely that you have another EditorFor that is causing the nullref exception here.

Upvotes: 1

Related Questions