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.

2
  • It also can be done via jquery/javascript i.e $('#dropid').val(2) Commented May 14, 2017 at 5:07
  • thanks zahid, how to get dropid? its dynamically loading ... when page load i need to display that value Commented May 14, 2017 at 5:34

1 Answer 1

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>
}
Sign up to request clarification or add additional context in comments.

2 Comments

wow! awesome. Thank you verymuch Ashiquzzaman
You are welcome.@SENA

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.