简体   繁体   中英

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.

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.

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