Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

asp.net mvc - DropDownListFor Not Selecting Value

I'm using the DropDownListFor helper method inside of an edit page and I'm not having any luck getting it to select the value that I specify. I noticed a similar question on Stackoverflow. The suggested workaround was to, "populate your SelectList in the view code". The problem is that I've already tried this and it's still not working.

<%= Html.DropDownListFor(model => model.States, new SelectList(Model.States.OrderBy(s => s.StateAbbr), "StateAbbr", "StateName", Model.AddressStateAbbr), "-- Select State --")%>

I have set a breakpoint and have verified the existence (and validity) of model.AddressStateAbbr. I'm just not sure what I'm missing.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

After researching for an hour, I found the problem that is causing the selected to not get set to DropDownListFor. The reason is you are using ViewBag's name the same as the model's property.

Example

public  class employee_insignia
{ 
   public int id{get;set;}
   public string name{get;set;}
   public int insignia{get;set;}//This property will store insignia id
}

// If your ViewBag's name same as your property name 
  ViewBag.Insignia = new SelectList(db.MtInsignia.AsEnumerable(), "id", "description", 1);

View

 @Html.DropDownListFor(model => model.insignia, (SelectList)ViewBag.Insignia, "Please select value")

The selected option will not set to dropdownlist, BUT When you change ViewBag's name to different name the selected option will show correct.

Example

ViewBag.InsigniaList = new SelectList(db.MtInsignia.AsEnumerable(), "id", "description", 1);

View

 @Html.DropDownListFor(model => model.insignia, (SelectList)ViewBag.InsigniaList , "Please select value")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...