Mvc 5 Multiselectlist selected not working - asp.net-mvc

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.

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" })

Include 'ALL' option in dropdownlist bind using ViewBag

I have bind the dropdownlist in view by Viewbag from controller as following :
ViewBag.test = from p in _userRegisterViewModel.GetEmpPrimary().ToList().Where(a => a.UserType_id != Convert.ToInt32(Session["loginUserType"].ToString()))
select new
{
Id = p.EmpId,
Name = p.First_Name.Trim() + " " + p.Last_Name.Trim()
};
In view I have bind as following :
#Html.DropDownListFor(model => model.EmpId, new SelectList(#ViewBag.test, "Id", "Name"),
new { #class = "form-control", id="ddlEmp" })
Now i want to Insert "ALL" and "--Select--" in this dropdownlist.. How can i do this..
Can anyone help me to do this..
Thanks in advance..
You can add a null option to the dropdownlist by using one of the overloads of DropDownlistFor() that accepts a optionLabel, for example
#Html.DropDownListFor(m => m.EmpId, new SelectList(#ViewBag.test, "Id", "Name"), "--select--", new { #class = "form-control", id="ddlEmp" })
which will generate the first option as <option value="">--select--</option>
However, if you want to include options with both "--select--" and "ALL" you will need to generate you own IEnumerable<SelectListItem> in the controller and pass it to the view. I would recommend using view model with a IEnumerable<SelectListItem> property for the options, but using ViewBag, the code in the controller would be
List<SelectListItem> options = _userRegisterViewModel.GetEmpPrimary()
.Where(a => a.UserType_id != Convert.ToInt32(Session["loginUserType"].ToString()))
.Select(a => new SelectListItem
{
Value = a.EmpId.ToString(),
Text = a.First_Name.Trim() + " " + a.Last_Name.Trim()
}).ToList();
// add the 'ALL' option
options.Add(new SelectListItem(){ Value = "-1", Text = "ALL" });
ViewBag.test = options;
Note that I have given the ALL option a value of -1 assuming that none of your EmpId values will be -1
Then in the view, your code to generate the dropdownlist will be
#Html.DropDownListFor(m => m.EmpId, (Ienumerable<SelectListItem>)ViewBag.test, "--select--", new { #class = "form-control" })
Not sure why your wanting to change the id attribute from id="EmpId" to id="ddlEmp"?
Then in the POST method, first check if ModelState is invalid (if the user selected the "--select--" option, a value of null will be posted and the model will be invalid), so return the view (don't forget to reassign the ViewBag.test property).
If ModelState is valid, then check the value of model.EmpId. If its -1, then the user selected "ALL", otherwise they selected a specific option.

Html.Dropdownlist selected value not working

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.

DropDownList Error in MVC3

After adding the class to the html.dropdownlist am facing the below error.
Error:'System.Web.Mvc.HtmlHelper' does not contain a definition for 'DropDownList' and the best extension method overload 'System.Web.Mvc.Html.SelectExtensions.DropDownList(System.Web.Mvc.HtmlHelper, string, string)' has some invalid arguments
<li>
#Html.LabelFor(m => m.BuildType)
#Html.DropDownList("BuildType", new { #class = "BuildType" })
#Html.ValidationMessageFor(m => m.BuildType)
</li>
<li>#Html.LabelFor(m => m.BuildMode)
#Html.DropDownList("BuildMode", new { #class = "BuildMode" })
#Html.ValidationMessageFor(m => m.BuildMode) </li>
<li>
Where are your list options? You need to provide a list of options via an IEnumerable<SelectListItem> object (see this overload).
So your model would have something like this:
public IEnumerable<SelectListItem> BuildModeOptions { get; set; }
And your view would pass the list into the helper:
#Html.DropDownList("BuildMode", Model.BuildModeOptions, new { #class = "BuildType" })
Or, since you're using the type-safe For versions on your other helpers, use DropDownListFor on this one as well:
#Html.DropDownListFor(m => m.BuildMode, Model.BuildModeOptions, new { #class = "BuildType" })
But keep in mind, Model.BuildMode is your selected value -- Model.BuildModeOptions is for your dropdown options.
You can use:
#Html.DropDownListFor(m => m.BuildType, (SelectList)Viewbag.YourSelectList, "Select Build type", new { #class = "BuildType" })
or
#Html.DropDownListFor(m => m.BuildType, Model.YourSelectList, "Select Build type", new { #class = "BuildType" })
When you use #Html.DropDownList, you specify a name for the dropdownlist... but you are missing the SelectList itself. I think that out of the box, the helper will try to use the name of the DropDownList (in your case "BuildType") to search in the ViewData collection for the SelectList.
When you use a #Html.DropDownListFor you don't use a name, but a lamda expression m => m.BuildType that will help you in same cases to not have harcoded names.
Your SelectList (the second parameter) can be grabbed from Viewbag or from a property in your Model.
The second parameter should be the list of items you want to show in the dropdown.
so It will look like :
#Html.DropDownListFor("BuildType", m.yourListofItems, new { #class = "BuildType" })

MVC4 SelectList not selected default object

My select list isn't selecting the default object being brought in through code.
I first create my SelectList like so:
public SelectList CreateSelectList(object objSelected = null)
{
return new SelectList(GetAll().OrderBy(s => s.NumericalValue), "PeriodID", "Name", objSelected);
}
My objSelected gets filled with a Guid that's associated with the PeriodID.
Inside my controller I define my viewbag variable to the new select list.
public ActionResult Edit(Guid id)
{
Classroom classroom = classroomRepository.GetByID(id);
ViewBag.PeriodID = periodRepository.CreateSelectList(classroom.PeriodID);
return View(classroom);
}
Then in my View here's how I'm displaying my SelectList:
<div class="control-group">
#Html.LabelFor(model => model.PeriodID, "Period", new { #class = "control-label" })
<div class="controls">
#Html.DropDownListFor(model => model.PeriodID, ViewBag.PeriodID as SelectList, String.Empty, new { #class = "span3" })
#Html.ValidationMessageFor(model => model.PeriodID)
</div>
</div>
You have two problems here. First, this:
#Html.DropDownListFor(model => model.PeriodID, ViewBag.PeriodID as SelectList,
String.Empty, new { #class = "span3" })
Change ViewBag.PeriodID to ViewBag.Periods or ViewBag.PeriodList. This is confusing, and there are a number of situations in which MVC will get confused if you use the same named object. It's just best to make sure everything is named differently.
Second, The SelectList class ignores the selecteditem member of the SelectListItem. It's not used at all. DropDownListFor will take the value of model.PeriodID and make it the selected value. However, I see in your code that those should be the same so I'm guessing the naming may be a factor here.

Resources