Search code examples
c#asp.netasp.net-mvcasp.net-mvc-4dropdownlistfor

MVC Display object value in dropdownlist in edit view of object collection


I have some problem in communicating data from controller to view and vise-versa. Here is my controller:

ViewBag.MANAGER_IDS = new SelectList(db.APP_USERS, "USER_ID", "USER_ID");
return View(app_users_manager);

What I want to do is to populate populate manager ids in a dropdownlist for each object (i.e. app_users_manager)

Following is my view:

@model List<HRM.Models.APP_USERS_MANAGER>
@{
    ViewBag.Title = "Edit managers";
}
@using (Html.BeginForm("Edit", "UserManager", FormMethod.Post)) {
    @Html.AntiForgeryToken()

    <table>
        <tr class="myidtr">
            <th>Manager role</th>
            <th>Manager</th>
        </tr>
        @for (int i = 0; i < Model.Count; i++)
        {
            <tr class="mytr">
                @Html.Hidden("app_users_manager[" + @i + "].USER_ID", Model[i].USER_ID)
                <td>
                    @Html.DisplayFor(modelItem => Model[i].APP_MANAGERS.MANAGER_DESCRIPTION)
                </td>
                <td>
                    @Html.DropDownList("app_users_manager[" + @i + "].USER_ID_MANAGER", ViewBag.USER_ID_MANAGER as List<SelectListItem>, "-Select manager-")
                </td>
            </tr>
        }
    </table>

    @Html.ValidationSummary(false)
    <p>
        <input type="submit" value="Save" />
    </p>
}

I am able to do so using the following:

@Html.DropDownList(Model[i].USER_ID_MANAGER, ViewBag.USER_ID_MANAGER as List<SelectListItem>, "-Select manager-", new { @Id = "Test"})

but then I do not get updated value in my controller. or if I do following then I am not be able to get value on the view:

@Html.DropDownList("USER_ID_MANAGER", ViewBag.USER_ID_MANAGER as List<SelectListItem>, "-Select manager-")

Can somebody suggest whats wrong in there? Any help is very much appreciated!!


Solution

  • Thanks for your valuable comments Stephen. I was able to view and persist changed values. For future references to similar problem to anyone, here is how I fixed it:

    public ActionResult Edit(string user_id)
    {
    ViewBag.USER_ID_MANAGER = new SelectList(db.APP_USERS, "USER_ID", "USER_ID");
                return View(app_users_manager);
    }
    
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(List<APP_USERS_MANAGER> app_users_manager)
    {
    return View(app_users_manager);
    }
    

    This is how my view looks:

    @Html.DropDownList("app_users_manager[" + @i + "].USER_ID_MANAGER", new SelectList(ViewBag.USER_ID_MANAGER, "Value", "Text", Model[i].USER_ID_MANAGER), "-Select manager-")