Html.Dropdownlist selected value not working - asp.net-mvc

In my project, Html.DropdownList could not display its selected value.It displays the initial value of the list.My controller and view codes are given below:
Controller:
public ActionResult Edit(int id = 0)
{
PERMISSION permission = permissionManager.Find(id);
ViewBag.MODULE_ID = new SelectList(moduleManager.GetAll(), "ID", "TITLE",permission.MODULE_ID);
return View(permission);
}
View :
#Html.DropDownList("MODULE_ID", (IEnumerable<SelectListItem>)#ViewBag.MODULE_ID, new { #class = "form-control" })
But if I write :
#Html.DropDownList("MODULE_ID", String.Empty)
It works fine.but I have to add the class="form-control".What should be solution?
UPDATE:
I have changed the ViewBag name from ViewBag.MODULE_ID to ViewBag.ModuleList. It may conflicts with the name of the dropdownlist. and now It works fine.

I have changed the ViewBag name from ViewBag.MODULE_ID to ViewBag.ModuleList. It may conflicts with the name of the dropdownlist. and now It works fine.

You are adding the form-control class in the wrong parameter. currently it is being added as the option label.
Use this:
#Html.DropDownList("MODULE_ID", (IEnumerable<SelectListItem>)#ViewBag.MODULE_ID, "-- Select --", new { #class = "form-control" })
On a side note, you should consider using a ViewModel class and doing away with both the magic string "MODULE_ID" and the ViewBag magic property. A ViewModel class allows you to strongly name things without casting, like this:
#Html.DropDownListFor(model => model.MODULE_ID, Model.Modules, "-- Select --", new { #class = "form-control" })
It's a subtle looking change but everything is compile time checked.

what works for me according to previous solution:
in controller:
ViewBag.VCenter = new SelectList(db.VirtualMachinesData.Where(x => x.IsVCenter == true).ToList(), "Id", "IPAddress","80"); ;
in View:
#Html.DropDownList("v", (IEnumerable<SelectListItem>)#ViewBag.VCenter, new { #class = "form-control" })
Important note: the name of dropdownlist -"v"- must be different from the name of viewbag -"VCenter"-, if same names it didn't work.

Related

Html.DropDownListFor Selected=true reset automatically in index view

I’m binding #html.DropdownListFor control via modal in mvc page.
My code as below in cshtml page,
#Html.DropDownListFor(a => a.stateId, Model.statelist, new { #id = "StateList", #class = "form-control" })
in above Model.Statelist is of type List<SelectListItem>
I checked the Model.statelist have 2nd item Selected=true by debugging code.
But after render page on browser, selecteditem goes to first item.
Can any one Suggest me.
I think you need to make the following change. I did notice, for first parameter you have used 'a', while for second parameter list you have have "Model".
#Html.DropDownListFor(model => model.stateId, model.statelist, new { #id = "StateList", #class = "form-control" })

DropDownListFor not setting selected value with different names

I feel like this is very simple and I have done my research here:
Research
But it is not working.
Controller:
ViewBag.OwnerValue = new SelectList(db.tableName, "ID", "AName", object.OwnerID);
View:
#Html.DropDownListFor(model => model.AID, ViewBag.OwnerValue as SelectList, new { #class = "form-control" })
In my research the answer said to change the name of the ViewBag property so that it doesn't match the actual property name.. so that's what I did and the selected value is still not being set.
Any help is appreciated.
You would need to set the model property AID before passing the result to View in your controller action:
ViewBag.OwnerValue = new SelectList(db.tableName, "ID", "AName");
model.AID = object.OwnerID;
return View(model);

Mvc 5 Multiselectlist selected not working

select element created with items in it, but "selected" properties not showing in html result. What i do wrong?
this code is working:
controller:
ViewBag.ProductTwistDirectionID = new SelectList(db.tblProductTwistDirection,
"ProductTwistDirectionID",
"ProductTwistDirectionName",
tblProduct.ProductTwistDirectionID);
view:
#Html.DropDownList("ProductTwistDirectionID",
null,
htmlAttributes: new { #class = "form-control" })
this code is not working: (selected items not selecting at render)
controller:
ViewBag.ProductUsePurposes = new MultiSelectList(db.tblProductUsePurpose,
"ProductUsePurposeID",
"ProductUsePurposeName",
tblProduct.ProductUsePurposes
.Select(x
=> x.ProductUsePurposeID)
.ToArray());
view:
#Html.DropDownListFor(model => model.ProductUsePurposes,
null,
new
{
#class = "chosen-select",
multiple = "multiple",
data_placeholder = "Choose use purposes",
style = "width: 400px;"
})
Your ViewBag member holding the select list cannot be named the same as your model property. ViewBag is used, in addition to ViewData and Request, to compose the ModelState object and whatever is in ModelState overrides the properties on your model.
Simply, you need to rename ViewBag.ProductUsePurposes to something like ViewBag.ProductUsePurposesChoices. Then, you should be fine.

MVC Edit View set selected dropdown list value with htmlAttribute overload

So I can easily set the select value of my drop-down list in my Edit View if I don't using the htmlAttributes overloaded method. So the below works:
Edit View razor
#Html.DropDownList("CategoriesId")
Controller
public ActionResult Edit(int? id)
{
if (id==null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Budget budget = db.BudgetData.Find(id);
if (budget == null)
{
return HttpNotFound();
}
ViewBag.CategoriesId = new SelectList(db.Categories, "Id", "Description", budget.CategoriesId);
return View(budget);
}
No problem with the above but I want to be able to set the class using the htmlAttributes without using jQuery or some similar way.
As soon as I change my Edit View to the below it now has a nice bootstrap class but the selected value for that record has now been lost and it it always just shows the first record. I'm sure its something simple but I'm new to MVC :)
New htmlAttribute Razor
#Html.DropDownList("CategoriesId", (IEnumerable<SelectListItem>)ViewBag.CategoriesId, new { #class="form-control"})
I have also tried the below controller code but to no avail.
ViewBag.CategoriesId = db.Categories.AsEnumerable().Select(s => new SelectListItem { Text = s.Description, Value = s.Id.ToString(), Selected = budget.CategoriesId == s.Id });
Thanx for the helps guys.
--EDIT FOR ANSWER INFO--
After finding out that my DDL with ViewBag.CategoriesId can't be the same as my model etc causing the above the question. I changed my ViewBag property to ViewBag.CategoriesDDL but then of course that's not in my model.
So for any non mvc pro's like myself here's what I did to fix that. I only changed the following in my Edit View:
#Html.DropDownList("CategoriesDDL", (IEnumerable<SelectListItem>)ViewBag.CategoriesId, new { #class = "form-control" })
To:
#Html.DropDownListFor(model => model.CategoriesId, ViewBag.CategoriesDDL as IEnumerable<SelectListItem>, new { #class = "form-control" })
Hopefully this question helps somebody out there :)

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.
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")
If you're doing it properly and using a model--unlike all these ViewBag weirdos--and still seeing the issue, it's because #Html.DropDownListFor(m => m.MyValue, #Model.MyOptions) can't match MyValue with the choices it has in MyOptions. The two potential reasons for that are:
MyValue is null. You haven't set it in your ViewModel. Making one of MyOptions have a Selected=true won't solve this.
More subtly, the type of MyValue is different than the types in MyOptions. So like, if MyValue is (int) 1, but your MyOptions are a list of padded strings {"01", "02", "03", ...}, it's obviously not going to select anything.
Try:
<%= Html.DropDownListFor(
model => model.AddressStateAbbr,
new SelectList(
Model.States.OrderBy(s => s.StateAbbr),
"StateAbbr",
"StateName",
Model.AddressStateAbbr), "-- Select State --")%>
or in Razor syntax:
#Html.DropDownListFor(
model => model.AddressStateAbbr,
new SelectList(
Model.States.OrderBy(s => s.StateAbbr),
"StateAbbr",
"StateName",
Model.AddressStateAbbr), "-- Select State --")
The expression based helpers don't seem to respect the Selected property of the SelectListItems in your SelectList.
While not addressing this question - it may help future googlers if they followed my thought path:
I wanted a multiple select and this attribute hack on DropDownListFor wasn't auto selecting
Html.DropDownListFor(m => m.TrainingLevelSelected, Model.TrainingLevelSelectListItems, new {multiple= "multiple" })
instead I should have been using ListBoxFor which made everything work
Html.ListBoxFor(m => m.TrainingLevelSelected, Model.TrainingLevelSelectListItems)
I also having similar issue and I solve it by as follows,
set the
model.States property on your controller to what you need to be selected
model.States="California"
and then you will get "California" as default value.
I encountered this issue recently. It drove me mad for about an hour.
In my case, I wasn't using a ViewBag variable with the same name as the model property.
After tracing source control changes, the issue turned out to be that my action had an argument with the same name as the model property:
public ActionResult SomeAction(string someName)
{
var model = new SomeModel();
model.SomeNames = GetSomeList();
//Notice how the model property name matches the action name
model.someName = someName;
}
In the view:
#Html.DropDownListFor(model => model.someName, Model.SomeNames)
I simply changed the action's argument to some other name and it started working again:
public ActionResult SomeAction(string someOtherName)
{
//....
}
I suppose one could also change the model's property name but in my case, the argument name is meaningless so...
Hopefully this answer saves someone else the trouble.
I know this is an old question but I have been having the same issue in 2020.
It turns out the issue was with the model property being called "Title", I renamed it to "GivenTitle" and it now works as expected.
From
Html.DropDownListFor(m => m.Title, Model.Titles, "Please Select", new { #class = "form-control" })
to
Html.DropDownListFor(m => m.GivenTitle, Model.GivenTitles, "Please Select", new { #class = "form-control" })
this problem is common. change viewbag property name to other then model variable name used on page.
One other thing to check if it's not all your own code, is to make sure there's not a javascript function changing the value on page load. After hours of banging my head against a wall reading through all these solutions, I discovered this is what was happening with me.
The issue at least for me was tied to the IEnumerable<T>.
Basically what happened was that the view and the model did not have the same reference for the same property.
If you do this
IEnumerable<CoolName> CoolNames {get;set;} = GetData().Select(x => new CoolName{...});}
Then bind this using the
#Html.DropDownListFor(model => model.Id, Model.CoolNames)
The View loses track of the CoolNames property,
a simple fix is just to add .ToList() After dooing a projection (.Select()) ;).
I had the same problem. In the example below The variable ViewData["DATA_ACREDITO_MODELO_INTEGRADO"] has a SelectListItem list with a default selected value but such attribute is not reflected visually.
// data
var p_estadoAcreditacion = "NO";
var estadoAcreditacion = new List<SelectListItem>();
estadoAcreditacion.Add(new SelectListItem { Text = "(SELECCIONE)" , Value = " " });
estadoAcreditacion.Add(new SelectListItem { Text = "SI" , Value = "SI" });
estadoAcreditacion.Add(new SelectListItem { Text = "NO" , Value = "NO" });
if (!string.IsNullOrEmpty(p_estadoAcreditacion))
{
estadoAcreditacion.First(x => x.Value == p_estadoAcreditacion.Trim()).Selected = true;
}
ViewData["DATA_ACREDITO_MODELO_INTEGRADO"] = estadoAcreditacion;
I solved it by making the first argument of DropdownList, different to the id attribute.
// error:
#Html.DropDownList("SELECT__ACREDITO_MODELO_INTEGRADO"
, ViewData["DATA_ACREDITO_MODELO_INTEGRADO"] as List<SelectListItem>
, new
{
id = "SELECT__ACREDITO_MODELO_INTEGRADO"
...
// solved :
#Html.DropDownList("DROPDOWNLIST_ACREDITO_MODELO_INTEGRADO"
, ViewData["DATA_ACREDITO_MODELO_INTEGRADO"] as List<SelectListItem>
, new
{
id = "SELECT__ACREDITO_MODELO_INTEGRADO"
...

Resources