0

On my index.cshtml the model is a list of Person. I want to display these Persons on the page. However, on the same page I want to show a dialog that allows a new Person to be created via ajax.

It seems like a violation of DRY to recreate the markup in the editor template inside the dialog.

A possible solution could be:

  • Create a partial with Person as model
  • Call @Html.EditorForModel
  • Call @Html.RenderPartial("_partial", new Person()) from index.cshtml

But this seems like unnecessary indirection that obfuscates the code.

Is there a pattern or best practice to use in this scenario?

Model for Person

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

EditorTemplate for person

@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>
Nformer
  • 91
  • 2
  • 7
  • 1
    It's good approach and/or practice... I don't understand your problem. – solrac May 22 '18 at 13:51
  • @carlosfcmendes its not a problem, rather a 1 line partial seems unnecessary. it seems like maybe there is a better inline solution? – Nformer May 22 '18 at 13:55

0 Answers0