Mvc List Strongly type View DropDownListFor not showing current value

偶尔善良 提交于 2019-12-12 01:24:22

问题


I have following dropdownlistfor control

@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 + "');" })

I bind this strongly type view like this @model List<MvcUI.Models.UserDetails>

In ViewBag.RelationShip I have following list

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;
}

I am passing List Of UserDetails model to my view. Here is my UserDetails Model

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
}

Suppose in a list I have 3 record. Out of them 2 records RelationShipId is null. If it's null then I am setting -1 which is -- Select --. In remaining one record I have RelationShipId suppose I have 13. When view opens It is binding -- Select -- for first two record. But for 3rd record it is not binding appropriate value from ViewBag. I can't figure it out where is the issue. Can some one help me to solve this?

EDIT

Here I have created one simple action i.e. user

[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);
}

Here is my 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>

In this View it is not binding relationId. By default it is showing -- Select -- instead of showing following relation

ajay - B
Vijay - M
John - F

Please see following image

New EDIT

Editor template 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>

Please See following screenshot


回答1:


Create a custom EditorTemplate for type of UserFriendDetails

In /Views/Shared/EditorTemplates/UserFriendDetails.cshtml

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

Then in the main view, pass the SelectList to the template using additional view data

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

This will generate the correct name attributes to bind to you collection, for example

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

and select the correct option based on the value of each RelationShipId property.

Side note: I suggest you remove the new { @id = "ddl_" + @item.UserID,... and use the default id generated by the helper. Its not clear what the onchange attribute is doing but I also suggest you use unobtrusive javascript rather than polluting your markup with behavior.




回答2:


As I mentioned in my comment, I can't quite figure out what you're asking, but what I can figure out is that you're doing a few things wrong here.

First, you should not be using "-1" for default.. You are using a nullable field RelationShipId, and you should make RelaitonShipId null when you want it unselected, then you use the "option label" default string parameter of DropDownListFor to place the text for this.

@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 + "');" })

This allows model binding and validation to work, so if you have a required validation, if RelationShipId is null ("--Select--" is selected) then it will fail to validate.




回答3:


I tried this solution for multiple dropdown on 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>

here listRelations is ViewBag of type var listRelations = ViewBag.RelationShip as List<IDTitleDTO>;



来源:https://stackoverflow.com/questions/29446590/mvc-list-strongly-type-view-dropdownlistfor-not-showing-current-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!