I have two ASP.NET MVC EF entities sharing an association:
When I am editing or creating the User
, I'd like to be able to attach one or more UserRole
s. So, my User
Create
view looks like this:
@model MyModels.UserViewModel
@{ ViewBag.Title = "Create"; }
@using (Html.BeginForm())
{
<fieldset>
<legend>User</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Username)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Username)
@Html.ValidationMessageFor(model => model.Username)
</div>
<!-- how to create an editor to add/remove roles -->
<div class="editor-label">
@Html.LabelFor(model => model.UserRoles)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.UserRoles)
@Html.ValidationMessageFor(model => model.UserRoles)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
Since Model.UserRoles
is initially empty, I get nothing in this line @Html.EditorFor(model => model.UserRoles)
. I tried adding a drop-down where I can select existing roles using JavaScript (I guess retrieved as partial view?), but I don't know how to append a selected role to the fieldset
so that it gets submitted.
How is this usually done in ASP.NET? I have been searching SO for a while but cannot find the appropriate solution.
To clarify, what I don't understand is how to add/append a new role to the client side, so that the submit button actually sends this inside the UserRoles
list.
(edit) Ok, I've found this: How to add an item to a list in a ViewModel using Razor and .NET Core. It says that I should fetch a partial view which is written to look like the inputs which would be generated by @Html.EditorFor
(with the next array index), and then append it using JavaScript.
That looks quite weird, is that really the correct approach?