Mvc List Strongly type View DropDownListFor not showing current value


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?


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

<img alt="enter image description here" class="b-lazy" data-src="https://i.stack.imgur.com/pCnCg.png" data-original="https://i.stack.imgur.com/pCnCg.png" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" />

<h2>New EDIT</h2>

Editor template UserDetails.cshtml

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


@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

<img alt="enter image description here" class="b-lazy" data-src="https://i.stack.imgur.com/E2wpg.png" data-original="https://i.stack.imgur.com/E2wpg.png" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" />


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 <a href="http://en.wikipedia.org/wiki/Unobtrusive_JavaScript" rel="nofollow">unobtrusive javascript</a> rather than polluting your markup with behavior.


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.


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


  • Check if NSString hasPrefix that is contained in NSArray
  • Adding and multiplying columns of a numpy array with another array
  • How to overcome the effect of navigation bar
  • use grep and awk to transfer data from .srt to .csv/xls
  • How to draw cross background via css which is responsive
  • How can I fill all space of a div 100% with 3 divs with the same size?
  • How to extract a plane from a 3D variable in FiPy (3D to 2D)
  • TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'
  • Safari PHP form submission -file upload hangs
  • How do I obtain a list of files that changed from svn over a date range?
  • How to get value from merged-cells in Excel document using OpenXML and C#
  • When executing an array of tasks asynchronously, shouldn't it take as long as the longest runni
  • Get current user from inside the model in Sails
  • SQL: Getting the physical size of a subset of a table
  • Can I have a variable number of URI parameters or key-value pairs in Laravel 4?
  • How do I remove all but some records based on a threshold?
  • How do I get the list of bad records that didn't load in Bigquery?
  • as3-flash: any way to access all the instances placed in different frames from document class?
  • Sequential (transactional) API calls in angular 4 with state management
  • How can the INSERT … ON CONFLICT (id) DO UPDATE… syntax be used with a sequence ID?
  • Does it make sense to call System.gc() and Thread.sleep() when working on Bitmaps?
  • Marklogic : Query response time is very high
  • Caching attributes in superclass
  • WPF - CanExecute dosn't fire when raising Commands from a UserControl
  • Why querying a date BC is changed to AD in Java?
  • Bad request using file_get_contents for PUT request in PHP
  • Record samples being played with OpenAL
  • How can I send an e-mail from a vbs script
  • Sails.js/waterline: Executing waterline queries in toJSON function of a model?
  • Dynamically accessing properties of knockoutjs observable array
  • Can Jackson SerializationFeature be overridden per field or class?
  • 'TypeError' while using NSGA2 to solve Multi-objective prob. from pyopt-sparse in OpenMDAO
  • Linker errors when using intrinsic function via function pointer
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • Codeigniter doesn't let me update entry, because some fields must be unique
  • How get height of the a view with gone visibility and height defined as wrap_content in xml?
  • how does django model after text[] in postgresql [duplicate]
  • LevelDB C iterator
  • Linking SubReports Without LinkChild/LinkMaster
  • How can i traverse a binary tree from right to left in java?