I have an issue where the selected value is not working for the Html.DropDownList helper method. See below:
This is My Controller:
public ActionResult Edit(int id = 0)
{
NewsEvent item = GetItem(id);
ViewBag.NewsItemId = new SelectList(ViewBag.NewsItemId.Items, "Id", "Name", item.NewsItemId);
return View(item);
}
This is my View:
@Html.DropDownList("NewsItemId",ViewBag.NewsItemId as SelectList, string.Empty,
new { @class = "form-control" })
However when I try the below in by view it works:
@Html.DropDownList("NewsItemId", string.Empty)
The below also works but since the field name does not match the model, it will not post correctly.
@Html.DropDownList("NewsItemIdDrop",ViewBag.NewsItemId as SelectList, string.Empty,
new { @class = "form-control" })
The reason I need to use the first option is so that I can add the class attribute to the control.
Could someone help me understand what I am doing wrong?
change to
ViewBag.NewsItemIdList
name changed. also change in controller.I tried lot of stuff but eventually got it working like this
In controller
And then in view I just put (I have the onchange event and class for dropdown too here but you can remove those if you want).
(Sorry about finnish in the text values and variable names, but those shouldn't matter :D)
change viewbag property name to other then model variable name used on page.
I did not like the fact that you can use
and it works. Then you need to add the 'class' attribute and suddenly it breaks. I saw one place working and another not working using the syntax
When I researched this, I determined the ViewBag.NewsItemId was actually a null in the view. So a working syntax, with the Model and ViewBag fields having the same name is
You should change the very name of the field of your DropDownList:
You have the same problem here:
Problem is in your ViewBag property name. Because it is same as your property in Model it will not work. You should just change name of your ViewBag prop to something else, like:
and on View