1

I need to display dropdown text based on DB values. I'm not able to find a solution.

DB Value:

RolesID  DeptID  UserID
2        1        100
5        2        200

View

@foreach (var gt in Model.RoleList)
{
    <tr>                    
        <td>@Html.DropDownListFor(m => m.Role, new SelectList(Model.Role, "RoleId", "RoleName",@gt.RoleId), new { @class = "form-control" })</td>
        <td>@Html.DropDownListFor(m => m.Plants, new SelectList(Model.Department, "DeptId", "DeptName", @gt.DeptId), new { @class = "form-control" })</td>

    @using (Ajax.BeginForm("deletedet", new AjaxOptions() { UpdateTargetId = "Edit-User", AllowCache = true, InsertionMode = InsertionMode.ReplaceWith }))
    {
        @Html.Hidden("userId", @gt.UserId)
        <td><p data-placement="top" data-toggle="tooltip" title="Delete"><button class="btn btn-danger btn-xs" data-title="Delete" data-toggle="modal" data-target="#myTable"><span class="glyphicon glyphicon-trash"></span></button></p></td>
    }

    </tr>
}

Model.RoleList - contains list of user role id and department id.

Model.Role - contains list of Roles(master table)

Question:

  • Is there any other way to display default text for dropdownlist?
  • Based on RoleId I have to select RoleName in that dropdown.

This dropdown will load dynamically.

shim
  • 9,289
  • 12
  • 69
  • 108
SENA
  • 119
  • 1
  • 2
  • 16

1 Answers1

1

If foreach loop @Html.DropDownListFor(m => m.Role, new SelectList(Model.Role, "RoleId", "RoleName",gt.RoleId), new { @class = "form-control" }) never working correctly, because in razor input/select/textarea create a unique html name attribute.But using foreach it can't do this. so use for loop or EditorTemplates rather than foreach.

Other wise you can generate the html but you can't send list of item in your action.

Example:

@for(var i = 0;i < Model.RoleList.Count;i++)
{
    <tr>
<td>@Html.DropDownListFor(m => Model.RoleList[i].RoleId, new SelectList(Model.Role, "RoleId", "RoleName", Model.RoleList[i].RoleId), new { @class = "form-control" })</td>
    </tr>
}
Ashiquzzaman
  • 5,129
  • 3
  • 27
  • 38