0

In MVC4, with the Razor view engine, we have a group of items that we wish to group in a partial view, so that we can reuse the code. Currently our main views we have something along the lines of:

<div class="editor-label">
  @Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
  @Html.TextAreaFor(model => model.Description, new { @id = "Common" })
  <div class="FormValidationText">
    @Html.ValidationMessageFor(model => model.Description)
  </div>
</div>

We want to be able to use this logic but with a wide variety of models, not all of which will want to use the model.Description.

For example, we would like to use model Foo, and create the above for the Foo.Bar property, but we also want to be able to use the Hello model's Hello.World property. These are all of type string, as you would expect since we want to handle the text input from the textarea.

What edits do we need to make in the partial view to say "Use some specified property of any given model, and understand it to be a property of that model, to generate these items". How, subsequently, do we work with the @{Html.RenderPartial(...)} method to ensure that we have passed the models property?

Please forgive me if this seems a little confused, I am still learning MVC and Razor views.

4

1 回答 1

2

正如您所期望的,这些都是字符串类型,因为我们要处理来自 textarea 的文本输入。

您可以编写一个编辑器模板~/Views/Shared/EditorTemplates/MyTemplate.cshtml

@model string
<div class="editor-label">
    @Html.LabelFor(model => model)
</div>
<div class="editor-field">
    @Html.TextAreaFor(model => model, new { @id = "Common" })
    <div class="FormValidationText">
        @Html.ValidationMessageFor(model => model)
    </div>
</div>

然后你可以这样使用你的观点:

@model Foo
...
@Html.EditorFor(x => x.Description, "MyTemplate")

或者:

@model Hello
...
@Html.EditorFor(x => x.World, "MyTemplate")

如果你命名你的模板~/Views/Shared/EditorTemplates/string.cshtml,你甚至不需要在调用 EditorFor 帮助器时指定它的名称:

@model Hello
...
@Html.EditorFor(x => x.World)

按照惯例,所有类型的属性都string将使用您的模板。

于 2013-08-02T11:43:43.217 回答