2017-05-13 51 views
2

动态地我应该加载下拉列表并显示选定的值。但成功加载下拉菜单,但未选择默认值。如何为DropDownListFor使用asp.net动态设置默认值mvc4

@ gt.PlantId - 整数, PlantId -integer

 @foreach (var gt in Model.RoleList) 
     { 
      <tr> 
       <td>@Html.DropDownListFor(Model => Model.Plants,new SelectList(Model.Plants,"PlantId","PlantName", @gt.PlantId))</td> 
       <td>@gt.PlantId</td> 
       <td>@gt.RoleId</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> 

     } 
+0

'@ Html.DropDownListFor(M = >格雷尔,新塞尔lectList(Model.Genres,“Id”,“Name”),“DEFAULT VALUE GOES HERES”,new {@class =“form-control”})' – Unbreakable

+0

请尝试上面的内容并做相应的更改。 “DEAFULT VALUE GOES GOES”将其替换为默认设置 – Unbreakable

+0

Hi Unbreakable,非常感谢。根据价值我必须显示文本。当我输入“默认值GOES HERE”在这个我的ID我越来越像错误不能转换为字符串 – SENA

回答

1

如果foreach循环@Html.DropDownListFor ,@Html.HidenFor, @Html.TextBoxFor或任何其他输入元素从来没有工作, 因为在剃刀input/select/textarea创建一个独特的HTML name/id属性。但使用foreach它不能这样做。 所以用于循环或EditorTemplates而不是foreach。

其他明智的,你可以生成的HTML,但你不能发送项目列表在你的行动。

例子:

型号:

public class UserEditorViewModel 
    { 
     public string UserId { get; set; } 
     public string RoleId { get; set; } 
     public string UserName { get; set; } 
     public IEnumerable<Roles> Roles { get; set; } 
    } 

EditorTemplates需要在视图中(默认)的任一Views/Shared/EditorTemplatesViews/ControllerName/EditorTemplates和名称存在应的object(Or Name of the Model)你想要的名称将其用作模板。

Editortemplates:

查看/共享/ EditorTemplates/UserEditorViewModel.cshtml

@model UserEditorViewModel 

<div class="form-group"> 
    @Html.DisplayNameFor(m => m.UserId) 
    @Html.EditorFor(m => m.UserId) 
</div> 
<div class="form-group"> 
    @Html.DisplayNameFor(m => m.UserName) 
    @Html.EditorFor(m => m.UserName) 
</div> 
<div class="form-group"> 
    @Html.DisplayNameFor(m => m.RoleId) 
    @Html.DropDownListFor(m => m.RoleId, new SelectList(Model.Roles,"RoleId","RoleName",Model.RoleId)) 
</div> 

检视:

@model UserEditorViewModel 

@using (Html.BeginForm("--Your Action--", "--Your Controller--"))//Or use Ajax.BeginForm if you need 
{ 
    @Html.EditorForModel() 
    <input type="submit" value="Save" /> 
} 
+0

嗨,非常感谢。其工作正常更多的问题是我想保存所有更改的下拉列表值。例如一个用户它会来多个角色和部门dropdownlist我想保存所有的下拉值。你能帮我吗。 – SENA

+0

简单你的动作收到类似'ActionName(List 模型)'。@ @ SENA – Ashiquzzaman