0

I have two ASP.NET MVC EF entities sharing an association:

enter image description here

When I am editing or creating the User, I'd like to be able to attach one or more UserRoles. 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?

Lou
  • 4,244
  • 3
  • 33
  • 72
  • You should not use the Entity models for views for this reason. Your view should rather use a view-model to separate your layers. In your view-model you can have a list of roles that get passed to your controller along with the user id. Lemme know if you require an example. – Vince Jan 20 '21 at 10:50
  • @Vince: thanks, actually `MyModels.UserViewModel` is a view model (it was misspelled), and I don't have a problem with passing the list of all roles, my real issue is how to add multiple roles to `UserRoles` on the client side and get this list in the controller method. It seems like binding a collection is quite painful in ASP.NET MVC, most examples use the `BeginCollectionItem` helper from github. Could you please provide an example of how this part is done? – Lou Jan 21 '21 at 20:25

0 Answers0