Selected not working in html.dropdownlist MVC - c#

I have the below code
person.State is Nullable string
Controller:
ViewBag.States = new List<SelectListItem>
{
new SelectListItem {Value = "", Text = "Please select", Selected = string.IsNullOrEmpty(person.State)},
new SelectListItem {Value = "ACT", Text = "ACT", Selected = person.State.ToLower() == "act"},
new SelectListItem {Value = "NSW", Text = "NSW", Selected = person.State.ToLower() == "nsw"},
new SelectListItem {Value = "NT", Text = "NT", Selected = person.State.ToLower() == "nt"},
new SelectListItem {Value = "QLD", Text = "QLD", Selected = person.State.ToLower() == "qld"},
new SelectListItem {Value = "SA", Text = "SA", Selected = person.State.ToLower() == "sa"},
new SelectListItem {Value = "TAS", Text = "TAS", Selected = person.State.ToLower() == "tas"},
new SelectListItem {Value = "VIC", Text = "VIC", Selected = person.State.ToLower() == "vic"},
new SelectListItem {Value = "WA", Text = "WA", Selected = person.State.ToLower() == "wa"}
};
View:
#{
List<SelectListItem> states = ViewBag.States;
}
...
...
...
#Html.DropDownList("State", states, new { id = "State", #class = "roleSelect" })
Even though one SelectListItem is Selected=true, in the output it is showing Please select. When I inspect the element in html output, none of the option has Select attribute.
Any suggestion?

Related

Set a selected value by default in List SelectList

I want to set a selected value in my select list by default.
Here I have this select list :
#{
List
<SelectListItem>
dateEcheancierCc = new List
<SelectListItem>
();
foreach (var dateEch in arrayDateEcheancierCc)
{
dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch },"Value","Text","Selected-value-by-default");
}
<div class="md-select px-0" style="min-width:0px">
#Html.DropDownList("DateEche", dateEcheancierCc, new { #class = "form-conrol" })
</div>
}
Here I'am trying to set "Selected-value-by-default" is selected by default but it is not working for me why ?
Here the Dropdownlist:
#Html.DropDownList("DateEche", dateEcheancierCc, new { #class = "form-conrol" })
dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch },"Value","Text","Selected-value-by-default");
change to like this
dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch, Selected = true });
make sure the item that you set "Selected = true" is the only one in list
I don't know your rule but you can try like this
for example : I have an array { "Jeffrey", "John", "Joe", "Josh" }, and I want set Jeffrey as default selected
if (dateEch == "Jeffrey")
dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch, Selected = true });
else
dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch });
Replace your DropdownList as below,
<div class="md-select px-0" style="min-width:0px">
#Html.DropDownList("DateEche",new SelectList(dateEcheancierCc,"Value","Text","Selected-value-by-default"), new { #class = "form-conrol" })
</div>
and selectList as
foreach (var dateEch in arrayDateEcheancierCc)
{
dateEcheancierCc.Add(
new SelectListItem() { Text = dateEch, Value = dateEch }
);
}
https://dotnetfiddle.net/RFgoD1
if your views have model then you can use like this
#Html.DropDownListFor(model => model.SelectedId, new SelectList(Model.SelectCollections, "Value", "Text", Model.ValueToBeSelectedInCollection))
You need to add Selected=true while building the SelectListItem.
foreach (var dateEch in arrayDateEcheancierCc)
{
dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch ,Selected = true });
}

How to get value from Drodownlist in C#

GetCurrency(countrydetials.Country) gives me currency of that specific country. But in my scenario, I only have two currencies in my Currency dropdownlist. If the country matches currency is not available in currency dropdownlist then by default it should select Indian Rupee.
Controller code
CountryDetials countrydetials = new CountryDetials();
var model = GetCurrency(countrydetials.Country);
countrydetials.Currency = model.FirstOrDefault().Currency;
View
#Html.DropDownListFor(m => m.Currency, new List<SelectListItem>
{
new SelectListItem {Value = "INR", Text="Indian Rupee" },
new SelectListItem {Value = "NPR", Text = "Nepalese Rupee" },
},
new { #class = "form-control" })
#Html.DropDownListFor(m => m.Country, new List<SelectListItem>
{
new SelectListItem {Value = "IND", Text = "India" },
new SelectListItem {Value = "NEP", Text = "Nepal" },
new SelectListItem {Value = "SIN", Text = "Singapore" },
new SelectListItem {Value = "USA", Text = "USA" },
},
new { #class = "form-control"})

How to use Grouping for DropDownListFor in mvc 4

I need to use a Grouping in mvc4. How can I do it with mvc 4 DropDownListFor controls?
Here is a example:
Here is my real code in .cshtml for DropDownListFor:
#Html.DropDownListFor(model => model.Category, new List<SelectListItem>{
new SelectListItem() {Text = "Sales/Marketing", Value="Sales/Marketing"},
new SelectListItem() {Text = "BPO/Call Center", Value="BPO/Call Center"},
new SelectListItem() {Text = "Receptionist/Front Office", Value="Receptionist/Front Office"},
new SelectListItem() {Text = "Cook", Value="Cook"},
new SelectListItem() {Text = "Aayah/Child Caretaker", Value="Aayah/Child Caretaker"},
new SelectListItem() {Text = "Gardener", Value="Gardener"},
new SelectListItem() {Text = "Security/Guard", Value="Security/Guard"},
new SelectListItem() {Text = "Construction/Laborer", Value="Construction/Laborer"},
new SelectListItem() {Text = "Garment Tailor/Textile", Value="Garment Tailor/Textile"},
new SelectListItem() {Text = "Office Helper", Value="Office Helper"},
new SelectListItem() {Text = "Maid who can Cook", Value="Maid who can Cook"},
new SelectListItem() {Text = "Data Entry/Back Office", Value=""}},
"-- Choose Category --", new { #id = "Country", #class = "form-control", #data_error = "Choose No. of Employees is required", #required = "required" })
Even I have try to install DropDownList Optgroup MVC 1.0.0 but its not able to install on VS2012
My application framework is 4
How can I do this in client side with DropDownListFor use grouping for category?
you dont need any nuget packages you can use grouping SelectListGroup with SelectListItem like this
#{
var group1 = new SelectListGroup() {Name = "German Cars"};
var group2 = new SelectListGroup() {Name = "Swedish Cars"};
}
#Html.DropDownListFor(model => model.Id, new List<SelectListItem>{
new SelectListItem() {Text = "Audi", Value="Audi",Group =group1},
new SelectListItem() {Text = "Mercedese", Value="Mercedese",Group =group1},
new SelectListItem() {Text = "Saab", Value="Saab",Group =group2},
new SelectListItem() {Text = "Volvo", Value="Volvo",Group =group2}},
"-- Choose Category --", new { #class = "form-control", #required = "required" })
Edit
or you can do it manually with looping like this
first create a class
public class DropdownData
{
public string Name { get; set; }
public string GroupName { get; set; }
public string Id { get; set; }
}
then in action
ViewBag.Dropdowndata= new List<DropdownData>()
{
new DropdownData(){GroupName = "German Cars",Id = "Audi",Name = "Audi"},
new DropdownData(){GroupName = "German Cars",Id = "Mercedese",Name = "Mercedese"},
new DropdownData(){GroupName = "Swedish Cars",Id = "Saab",Name = "Saab"},
new DropdownData(){GroupName = "Swedish Cars",Id = "Volvo",Name = "Volvo"},
};
you can also use ViewModel instead of Viewbag
and finally in view
<select name="Category" id="Country" class="form-control" data_error="Choose No. of Employees is required" required="required">
<option value="">-- Choose Category --</option>
#{
string group = null;
foreach (var groups in (List<DropdownData>) ViewBag.Dropdowndata)
{
if (group != groups.GroupName)
{
group = groups.GroupName;
<optgroup label="#group">
#foreach (var data in (List<DropdownData>) ViewBag.Dropdowndata)
{
if (group == data.GroupName)
{
<option value="#data.Id">#data.Name</option>
}
}
</optgroup>
}
}
}
</select>

ASP.NET MVC Dropdown List From SelectList

I am building the following SelectList in my controller.
var u = new NewUser();
u.UserTypeOptions = new SelectList(new List<SelectListItem>
{
new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
new SelectListItem { Selected = false, Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
new SelectListItem { Selected = false, Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
});
return u;
And displaying it on my view like this:
#Html.DropDownListFor(m => m.UserType, Model.UserTypeOptions)
It looks like I am giving it a valid set of SelectListItems in what should be a pretty straightforward dropdown list, but instead of getting a valid <option> list with good values and text, I get this:
<select data-val="true" data-val-range="A user type must be selected." data-val-range-max="2" data-val-range-min="1" data-val-required="The UserType field is required." id="UserType" name="UserType" class="input-validation-error">
<option>System.Web.Mvc.SelectListItem</option>
<option>System.Web.Mvc.SelectListItem</option>
<option>System.Web.Mvc.SelectListItem</option>
</select>
What gives? As far as I can tell, this should work.
You are missing setting the Text and Value field in the SelectList itself. That is why it does a .ToString() on each object in the list. You could think that given it is a list of SelectListItem it should be smart enough to detect this... but it is not.
u.UserTypeOptions = new SelectList(
new List<SelectListItem>
{
new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
new SelectListItem { Selected = false, Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
new SelectListItem { Selected = false, Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
}, "Value" , "Text", 1);
BTW, you can use a list or array of any type... and then just set the name of the properties that will act as Text and Value.
I think it is better to do it like this:
u.UserTypeOptions = new SelectList(
new List<SelectListItem>
{
new SelectListItem { Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
new SelectListItem { Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
}, "Value" , "Text");
I removed the -1 item, and the setting of each item selected true/false.
Then, in your view:
#Html.DropDownListFor(m => m.UserType, Model.UserTypeOptions, "Select one")
This way, if you set the "Select one" item and don't set one item as selected in the SelectList, the UserType will be null (the UserType need to be int? ).
If you need to set one of the SelectList items as selected, you can use:
u.UserTypeOptions = new SelectList(options, "Value" , "Text", userIdToBeSelected);
As one of the users explained in the comments:
The 4th option of the SelectList constructor is ignored when binding to a property using DropDownListFor() - it is the property's value that determines what is selected.
Just try this in razor
#{
var selectList = new SelectList(
new List<SelectListItem>
{
new SelectListItem {Text = "Google", Value = "Google"},
new SelectListItem {Text = "Other", Value = "Other"},
}, "Value", "Text");
}
and then
#Html.DropDownListFor(m => m.YourFieldName, selectList, "Default label", new { #class = "css-class" })
or
#Html.DropDownList("ddlDropDownList", selectList, "Default label", new { #class = "css-class" })
Try this, just an example:
u.UserTypeOptions = new SelectList(new[]
{
new { ID="1", Name="name1" },
new { ID="2", Name="name2" },
new { ID="3", Name="name3" },
}, "ID", "Name", 1);
Or
u.UserTypeOptions = new SelectList(new List<SelectListItem>
{
new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
new SelectListItem { Selected = false, Text = "Homeowner", Value = "2"},
new SelectListItem { Selected = false, Text = "Contractor", Value = "3"},
},"Value","Text");
var selectList = new List<SelectListItem>();
selectList.Add(new SelectListItem {Text = "Google", Value = "Google"}) ;
selectList.Add(new SelectListItem {Text = "Other", Value = "Other"}) ;

Selected value missed if use model in DropDownListFor()

I am having trouble this DropDownListFor()
I have test controller:
model.COUNTRYNAME = "Swizerland";
ViewBag.Selecter = new SelectList(new[]
{
new SelectListItem { Text = "USA", Value = "USA" },
new SelectListItem { Text = "Swizerland", Value = "Swizerland", Selected =true},
new SelectListItem { Text = "Russia", Value = "Russia" },
}, "Text", "Value", model.COUNTRYNAME);
in View
#Html.DropDownListFor(x => Model.COUNTRYNAME , (SelectList)ViewBag.Selecter)
The DropDownListFor does not have select value, it always select first value.
What is wrong?
If i use DropDownList
#Html.DropDownList("COUNTRYNAME" , (SelectList)ViewBag.Selecter)
It also don't work.
But if I use
#Html.DropDownListFor("AAAAAAA" , (SelectList)ViewBag.Selecter)
It's work fine and select 2nd value! What happens? I don't understand.
Thanks
Try like this:
model.COUNTRYNAME = "Swizeland";
ViewBag.Selecter = new[]
{
new SelectListItem { Text = "USA", Value = "USA" },
new SelectListItem { Text = "Swizeland", Value = "Swizeland" },
new SelectListItem { Text = "Russia", Value = "Russia" },
};
return View(model);
and in the view:
#Html.DropDownListFor(
x => x.COUNTRYNAME,
(IEnumerable<SelectListItem>)ViewBag.Selecter
)
but a better way is to use a view model:
model.SelectedCountry = "Swizeland";
model.Countries = new[]
{
new SelectListItem { Text = "USA", Value = "USA" },
new SelectListItem { Text = "Swizeland", Value = "Swizeland" },
new SelectListItem { Text = "Russia", Value = "Russia" },
};
return View(model);
and in the view:
#Html.DropDownListFor(x => x.SelectedCountry, Model.Countries)

Categories