Mvc List强类型View DropDownListFor不显示当前值

时间:2015-04-04 12:49:07

标签: c# asp.net-mvc html.dropdownlistfor

我有以下dropdownlistfor控件

@Html.DropDownListFor(m => item.RelationShipId, new SelectList(ViewBag.RelationShip,"Id", "Title"), new { @id = "ddl_" + @item.UserID, @class = "form-control", onchange = "update(this,'" + @item.UserID + "','" + @item.SentByUserId + "');" })

我绑定了这个强类型视图,如@model List<MvcUI.Models.UserDetails>

ViewBag.RelationShip我有以下列表

public static List<IDTitleDTO> DataTableToRelationshipList(this DataTable table)
{
        var list = table.AsEnumerable()
            .Select(dr =>
                new IDTitleDTO
                {
                    Id = dr.Field<int>("RelationShipId"),
                    Title = dr.Field<string>("RelationShipName")
                }).ToList();
        return list;
}

我正在将UserDetails模型列表传递给我。这是我的UserDetails模型

public class UserFriendDetails
{
    public string UserID { get; set; }
    public string UserName { get; set; }
    public string Firstname { get; set; }
    public int? RelationShipId { get; set; }
    ....
    ...
    Other fields
}

假设在列表中我有3条记录。其中2条记录RelationShipId为null。如果它为null,那么我设置为-1,即 - 选择 - 。在剩下的一条记录中,我有RelationShipId,假设我有13.当视图打开它是绑定 - 选择 - 前两条记录。但是对于第三个记录,它没有从ViewBag绑定适当的值。我无法弄清楚问题出在哪里。有人可以帮我解决这个问题吗?

修改

这里我创建了一个简单的操作,即用户

[AllowAnonymous]
public ActionResult User()
{
    var model = new List<UserDetails>();
    model.Add(new UserDetails { Id = 1, Fname = "ajay", RelationId = 3});
    model.Add(new UserDetails { Id = 2, Fname = "vijay", RelationId = 1 });
    model.Add(new UserDetails { Id = 3, Fname = "John", RelationId = 2 });

    var rList = new List<IdTitleDTO>();
    rList.Add(new IdTitleDTO { Id = 1 , Title = "M"});
    rList.Add(new IdTitleDTO { Id = 2, Title = "F" });
    rList.Add(new IdTitleDTO { Id = 3, Title = "B" });

    ViewBag.Rel = rList;
    return View(model);
}

这是我的user.cshtml

@model List<WebApplicationDropDown.Models.UserDetails>
<table class="table">
    <tr>
        <th>
            Fname
        </th>
        <th></th>
    </tr>

    @*@foreach (var item in Model) {*@
    @for (int i = 0; i < Model.Count(); i++)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => Model[i].Fname)
            </td>
            <td>
                @Html.DropDownListFor(modelItem => Model[i].RelationId, new SelectList(ViewBag.Rel, "Id", "Title"), "--Select--")
            </td>
        </tr>
    }
</table>

在此视图中,它不是绑定relationId。默认情况下,它显示的是-- Select --,而不是显示以下关系

ajay - B
Vijay - M
John - F

请参阅以下图片

enter image description here

新编辑

编辑模板UserDetails。cshtml

@model WebApplicationDropDown.Models.UserDetails


@Html.DropDownListFor(m => m.RelationId, (SelectList)ViewData["RelationShipList"])

View.cshtml

@model IEnumerable<WebApplicationDropDown.Models.UserDetails>
<table class="table">
    <tr>
        <th>
            Fname
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Fname)
            </td>
            <td>
                @*@Html.DropDownListFor(modelItem => item.RelationId, new SelectList(ViewBag.Rel, "Id", "Title"), "--Select--")*@
                @Html.EditorFor(m => m, new { RelationShipList = new SelectList(ViewBag.Rel, "Id", "Title") })
            </td>
        </tr>
    }
</table>

请参见以下屏幕截图

enter image description here

3 个答案:

答案 0 :(得分:1)

EditorTemplate

类型创建自定义UserFriendDetails

/Views/Shared/EditorTemplates/UserFriendDetails.cshtml

@model UserFriendDetails
@Html.TextBoxFor(m => m.UserName)
....
@Html.DropDownLstFor(m => m.RelationShipId, (SelectList)ViewData["RelationShipList"])

然后在主视图中,使用其他视图数据将SelectList传递给模板

@model IEnumerable<UserFriendDetails>
....
@Html.EditorFor(m => m, new { RelationShipList = new SelectList(ViewBag.RelationShip,"Id", "Title") })

这将生成要绑定到您的集合的正确名称属性,例如

<select name="[0].RelationShipId" ..>
<select name="[1].RelationShipId" ..>

并根据每个RelationShipId属性的值选择正确的选项。

附注:我建议您删除new { @id = "ddl_" + @item.UserID,...并使用帮助程序生成的默认id。我不清楚onchange属性在做什么,但我也建议你使用unobtrusive javascript而不是用行为来污染你的标记。

答案 1 :(得分:0)

正如我在评论中提到的,我无法弄清楚你在问什么,但我能弄明白的是你在这里犯了一些错误。

首先,你不应该使用&#34; -1&#34;默认情况下..您正在使用可空字段RelationShipId,并且当您想要取消选择时,您应该使RelaitonShipId为null,然后使用&#34;选项标签&#34; DropDownListFor的默认字符串参数,用于放置此文本。

@Html.DropDownListFor(m => item.RelationShipId, 
     new SelectList(ViewBag.RelationShip,"Id", "Title"), 
     "--Select--", 
     new { @id = "ddl_" + @item.UserID, @class = "form-control", 
       onchange = "update(this,'" + @item.UserID + "','" + @item.SentByUserId + "');" })

这允许模型绑定和验证工作,所以如果你有一个必需的验证,如果RelationShipId为null(&#34; - 选择 - &#34;被选中),那么它将无法验证。

答案 2 :(得分:0)

我在View

上尝试使用此解决方案进行多次下拉
<select class="form-control" id="ddl_@item.UserID" name="ddl_@item.UserID" onchange = "update(this,'@item.UserID','@item.SentByUserId');">
    @foreach (var rel in listRelations)
    {
        <option @if (string.Compare(item.RelationShipId.ToString(), rel.Id.ToString(), true) == 0)
                { @Html.Raw("selected")  } value="@rel.Id">@rel.Title</option>
    }
</select>

此处listRelationsViewBag

类型的var listRelations = ViewBag.RelationShip as List<IDTitleDTO>;