ASP.NET MVC使用编辑器模板进行对象创建

时间:2018-05-22 13:44:02

标签: asp.net-mvc dry razor-pages code-standards

在我的index.cshtml上,模型是Person列表。我想在页面上显示这些人物。但是,在同一页面上,我想显示一个允许通过ajax创建新Person的对话框。

在对话框内的编辑器模板中重新创建标记似乎违反了DRY。

可能的解决方案可能是:

  • 使用Person作为模型创建部分
  • 致电@ Html.EditorForModel
  • 从index.cshtml调用@ Html.RenderPartial(“_ partial”,new Person())

但这似乎是混淆代码的不必要的间接。

在这种情况下是否有使用模式或最佳做法?

人物模型

public class Person
    {
        public string Name{ get; set; }
        public string Email { get; set; }
    }

人物的EditorTemplate

@model Person

<div class="form-group">
    @Html.LabelFor(model => model.Name)
    @Html.EditorFor(model => model.Name)
</div>

<div class="form-group">
    @Html.LabelFor(model => model.Email)
    @Html.EditorFor(model => model.Email)
</div>

Index.cshtml

@model Person[]

<ul>
@foreach (var person in Model)
{
    <li>@person.Name</li>
}
</ul>
<div class="modal" id="new">
    <div class="modal-dialog">
        <div class="modal-content">
            @using (Ajax.BeginForm("create", "contacts", new AjaxOptions() { }))
            {
                <div class="modal-header">
                    Create person
                </div>
                <div class="modal-body">
                    <--- use editor template ? <---
                    @Html.AntiForgeryToken()
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn">Ok</button>
                </div>
            }
        </div>
    </div>
</div>

0 个答案:

没有答案