Adding Multiple Static options to a Drop-Down in ASP.NETMVC - asp.net-mvc

I want to add two default options to my dropdowns in asp.net MVC using the html helper class, they are "--Please Select--" and "--Other--".
I can add one static option using
<%= Html.DropDownList("ddlserviceGroup",
(IEnumerable<SelectListItem>)ViewData["ServiceGroups"], "--Select Item--")%>
But i need to add two options and can't seem to figure it using the HTML helper class

The existing helper doesn't allow this. I'd suggest adding the options in the controller or perhaps writing your own extension method.
var serviceGroups = db.Groups
.Select( g => new SelectListItem
{
Text = g.Name,
Value = g.ID
})
.ToList();
// prepend to list
serviceGroups.Insert( 0, new SelectListItem
{
Text = "--Select Item --",
Value = string.Empty
} );
// add at end
serviceGroups.Add( new SelectListItem
{
Text = "-- Other -- ",
Value = ????
});
ViewData["ServiceGroups"] = serviceGroups;
In View
<%=
Html.DropDownList("ddlserviceGroup",
(IEnumerable<SelectListItem>)ViewData["ServiceGroups"]
%>

Related

Why doesn't Bootstrap Select show selected value when I include a default?

When I have an object with a value set, it is only shown initially if I leave out the "--Select--" parameter.
Any idea why that would be?
#Html.DropDownListFor(m => m.FlightDetails.AirlineId, ViewBag.AirlineList as SelectList, "--Select--", new { #class = "form-control selectpicker", #data_live_search = "true", #id = flight.Id + "AirlineId" })
Server-side:
You should set a default value for third params, look like this (Pay attention to SelectedDefaultValueHere)
var ViewBag.AirlineList = new SelectList(`listOfItemHere`,
"ValueOfDropdownItem",
"TextToDisplay",
SelectedDefaultValueHere);
Or You can set Selected of SelectListItem like this
new SelectListItem()
{
Value = "anyValue",
Text = "AnyText",
Selected = true
};
I found that this was my issue: https://stackoverflow.com/a/52431696/6591937.
I can't set the selected value when creating the SelectList because I'm using the same SelectList in more that one place and they all can have different values.
The way I resolved it in my case was that I passed in "--Select--" and I set the value via javascript (as I'm accessing it only via javascript anyway).

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.

Set the first item's value in DDL (MVC4) to null

I have a DDL in my view and i read items and values of this DDL from DB like this :
ViewBag.ContentGroup = new SelectList(obj.GetContentGrouplist(), "Id", "Name");
I put it in viewbag and i read the viewbag from the view like this :
<div class="editor-label">
#Html.LabelFor(model => model.ContentGroupFKId)
</div>
<div class="editor-field">
#Html.DropDownListFor(x => x.ContentGroupFKId, (SelectList)ViewBag.ContentGroup)
#Html.ValidationMessageFor(model => model.ContentGroupFKId)
</div>
So i need a DDL that the first item of that be null how can i do that?
I tried this but it doesn't work:
#Html.DropDownListFor(x => x.ContentGroupFKId,new SelectList(new List<Object> {new {value = null, text = "Select"} (SelectList)ViewBag.ContentGroup)
Best regards.
I don't think you can. Whatever value you provide is going to be used to generate html in the form of a select list, which doesn't support null. As long as you have a DropDownListFor, it is going to set a value, even if it is empty. The best thing you can do is make the first value a "Please select an item" option and set it to null server side.
There isn't a great way to add the "Please Select" option (at least none that I have seen. People are welcome to correct me though!), but there are a few ways to do it. One would be to create a dummy content group that just has a name and id.
var contentGroups = obj.GetContentGrouplist();
contentGroups.Insert(0, new ContentGroup{Id = "0", Name = "Please select a content group"};
ViewBag.ContentGroup = new SelectList(contentGroups, "Id", "Name");
Or you can create an object (which you would use anywhere you needed this functionality) that just holds a text and value property and then manually add all of your content groups to it, including the empty one.
class DropDownListOption{
public string Text{get;set;}
public string Value{get;set;}
}
then in your code
var contentGroups = obj.GetContentGrouplist();
var options = new List<DropDownListOption>();
options.Add(new DropDownListOption{ Id = "0", Text = "Please select a content group"};
foreach(var group in contentGroups)
{
options.Add(new DropDownListOption{ Id = group.Id, Text = group.Name};
}
ViewBag.ContentGroup = new SelectList(options, "Id", "Name");
Both of these options will work. I like the second option better because you can create a generic method of handling all drop down lists a certain way. You will have to handle ContentGroups with an ID of 0 as being null when the user submits the form, but at least it is a way of tracking it.
If I think of another way ill add it.

Show tooltip(or title) message on every dropdown list items

I’m using a custom dropdownlist and binding elements dynamically, but here I want to show a tooltip message on every items of dropdown list.
View Code:
#Html.DropDownListFor(m => m.Industry,Model.IndustryList, "All", new { #style = "width:258px;", #class = "drpDown" })
Controller code:
IEnumerable<SelectListItem> IndustryList= EntityModel<T>.Where(m => m.t == “something”).ToList().Select(c => new SelectListItem { Text = t.Name, Value = t.Value);
So let me know is there any way to set title on every option items within select tag.
No, the standard Html.DropDownListFor helper doesn't support setting any attributes on the <option> tags except the standard ones (value and selected). You could write a custom helper to achieve that. You may check this example as well as this one.
I would also probably go for Darin's answer, you need a custom drop down list.
A quick (and dirty) alternative might be to loop through manually and create your select list and set the title value on the option.
On your controller, maybe populate a view model as such (I'm just using an anonymous object as an example):
var SelectListViewModel = new[] {
new {
Text = "One",
Title = "I'm One Title",
Value = "1"
},
new {
Text = "Two",
Title = "I'm Two Title",
Value = "2"
}
};
and in your view:
<select>
#foreach (var item in SelectListViewModel)
{
<option title="#item.Title" value="#item.Value">#item.Text</option>
}
</select>
Not the cleanest, but hopefully might be helpful for someone.

ASP.NET MVC DropDownListFor does not honour SelectListItem.Selected

I am using DropDownListFor to render a dropdown list in a view. Somehow the rendered list does not select the SelectListItem with Selected set to true.
In the controller action:
var selectList = sortedEntries.Select(entry => new SelectListItem
{
Selected = entry.Value.Equals(selectedValue),
Text = entry.Value,
Value = entry.Id
});
return View(new DropDownListModel
{
ListId = id,
SelectList = selectList,
OptionLabel = "Click to Select"
});
In the view:
<%= Html.DropDownListFor(m => m.ListId,
Model.SelectList,
Model.OptionLabel,
new {#class="someClass"}) %>
I have tried the following:
make sure that there is one and only one items with Selected set to true.
remove the option label argument.
remove the HTML attribute object.
use SelectList in DropDownListFor:
Html.DropDownListFor(m => m.ListId,
new SelectList(Model.SelectList, "Value", "Text",
new List<SelectListItem>(Model.SelectList).Find(s => s.Selected)),
new {#class="someClass"})
Any suggestions as to what went wrong?
EDIT:
more information:
This action is a child action, called by another view with HTML.RenderAction
DropDownListFor will always select the value that the listbox is for, so in this case it will look at the value of ListId and make that item in the list selected. If ListId is not found in the list, the first item (or default text) will be selected. If you want a list that selects based on the selected attribute use DropDownList (without the For, in that case you have to name it yourself).
So in your case this would work:
var selectList = sortedEntries.Select(entry => new SelectListItem
{
Text = entry.Value,
Value = entry.Id
});
return View(new DropDownListModel
{
ListId = selectedValue,
SelectList = selectList,
OptionLabel = "Click to Select"
});
I got the same problem on the same model (with the other models in the decision no problem)
Does not work:
#Html.DropDownListFor(o => o.Drivers.ValueListItems.Value, Model.Drivers.ValueListItems, new { size = Model.Drivers.ValueSizeList, Multiple = "multiple" })
Works perfectly, the elements selected:
#Html.DropDownListFor(o => o.Drivers.ValueListItems.ToDictionary(u=>u.Value).Values, Model.Drivers.ValueListItems, new { size = Model.Drivers.ValueSizeList, Multiple = "multiple" })
Try like this:
var selectList = sortedEntries.Select(entry => new SelectListItem
{
Text = entry.Value,
Value = entry.Id
});
return View(new DropDownListModel
{
// The drop down list is bound to ListId so simply set its value
// to some element value in the list and it will get automatically
// preselected
ListId = selectedValue,
SelectList = selectList,
OptionLabel = "Click to Select"
});
and in the view:
<%= Html.DropDownListFor(
m => m.ListId,
new SelectList(Model.SelectList, "Value", "Text"),
Model.OptionLabel,
new { #class = "someClass" }
) %>
There could be one more gotcha: you are trying to change the selected value in a POST action. For example you rendered a form, the user selected some value in the dropdown, submitted the form and in your POST action you do some processing on this selected value and when you redisplay the view you want the drop down list to have some other value selected. In this case you will have to remove the initial selection which is contained in the ModelState or the Html helper will ignore the selected value in the model:
// do this before returning the view and only if your scenario
// corresponds to what I described above
ModelState.Remove("ListId");
The solution for this problem is simpler that we all think...
All we need to do is set the property on the view model for the element that the dropdown is bound to - i.e: ListId = 3 for example
this way when we do this
Html.DropDownListFor(m => m.ListId,
new SelectList(Model.SelectList, "Value", "Text",
new List<SelectListItem>(Model.SelectList).Find(s => s.Selected)),
new {#class="someClass"})
the HtmlHelper will automatically pick up the default value to display on the DropDownList
simples!
Hope it may help you and all the others - like me! - that have lost a lot of time searching for a solution for this apparent issue.

Resources