Reputation: 468
Mvc3 dropdownlistFor is deriving me crazy!!! I have two selects with the same code (different tevt and values) but one of them not works. here is my Controller code:
[Authorize(Roles = "admins")]
public ActionResult Edit(int id = -1)
{
Advertise Advertise = db.Advertises.Find(id);
if (null == Advertise)
return View("ProductNotFound");
var selectListItems = new List<SelectListItem>();
selectListItems.Add(new SelectListItem { Text = "A", Value = "A", Selected = ("A" == Advertise.Class) });
selectListItems.Add(new SelectListItem { Text = "B", Value = "B", Selected = ("B" == Advertise.Class) });
selectListItems.Add(new SelectListItem { Text = "C", Value = "C", Selected = ("C" == Advertise.Class) });
selectListItems.Add(new SelectListItem { Text = "D", Value = "D", Selected = ("D" == Advertise.Class) });
ViewBag.Class = new SelectList(selectListItems, "Value", "Text",Advertise.Class);
var selectListItems2 = new List<SelectListItem>();
selectListItems2.Add(new SelectListItem { Text = "Image", Value = "Image", Selected = ("Image" == Advertise.FileType) });
selectListItems2.Add(new SelectListItem { Text = "Flash", Value = "Flash", Selected = ("Flash" == Advertise.FileType) });
ViewBag.Type = new SelectList(selectListItems2, "Value", "Text",Advertise.FileType);
return View(Advertise);
}
and here is my view code:
<tr>
<td class="label">
@Html.LabelFor(model => model.Class) :
</td>
<td class="editor-field">
@Html.DropDownListFor(model => model.Class, (SelectList)ViewBag.Class)
@Html.ValidationMessageFor(model => model.Class)
</td>
</tr>
<tr>
<td class="label">
@Html.LabelFor(model => model.FileType) :
</td>
<td class="editor-field">
@Html.DropDownListFor(model => model.FileType, (SelectList)ViewBag.Type)
@Html.ValidationMessageFor(model => model.FileType)
</td>
</tr>
the secound select works perfectly and the first one (class) doesn't select the selected item on page load.
and for the record, the value stored in the database is C. please help!!!
Upvotes: 0
Views: 973
Reputation: 468
What a ...!!!!
I found out the reason of not working select is: the name of my variable (ViewBag.Class) is the same as my Field in the model!!! I change ViewBag.Class to ViewBag.glass (just to change the name) and it worked!!! thanks anyway. I hope it helps somebody which has this problem!!!
Upvotes: 3