olwg199
olwg199

Reputation: 15

I can't get the model from the view

can somebody help me?

I have a model:

public class EditUserVM
{
    public string Role {get;set;}
    public IEnumerable<SelectListItem> AllRoles { get; set; }
}

I have a controller:

public class AdminController : Controller
    {
            // GET: Admin/Admin/EditUser/id
            [HttpGet]
            public ActionResult EditUser(string id)
            {
                ApplicationUser user = UserManager.FindById(id);
                EditUserVM model;
                //model initialization
                return View(model);
            }

            // POST: Admin/Admin/EditUser
            [HttpPost]
            [ValidateAntiForgeryToken]
            public async Task<ActionResult> EditUser(EditUserVM model)
            {
                if (!ModelState.IsValid)
                {
                    return View(model);
                }
            //code
                return View(model);
            }
    }

And I have a view:

@model EditUserVM
@using (Html.BeginForm())
{
        <div class="form-group">
            @Html.LabelFor(model => model.Role, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("Role", Model.AllRoles, new { @class= "btn btn-light"})
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-success" />
            </div>
        </div>
}

But when I click on the save button, then in the post controller action I don’t get model.AllRoles I mean, that model.AllRoles == null. How can I get these values?

Upvotes: 1

Views: 41

Answers (1)

Pieter
Pieter

Reputation: 46

When the user submits the form (which then generates the callback to the [HttpPost]-variant of your EditUser method), the browser only submits the selected value of the drop down list, and not the entire list of possible selections. On the server side, an instance of the viewmodel is created and populated with what the browser sent. Since the browser hasn't sent the list of all possible options, that field is empty in your ViewModel.

This behavior makes sense. You're not interested in the list of possibilities (in fact, you already KNOW that list, because you sent it to the browser in the [HttpGet] method). You're only interested in the actual value that the user selected. If the ModelState is not valid, and you use that ViewModel to generate a new View, you need to repopulate AllRoles again.

Upvotes: 1

Related Questions