ASP.NET MVC Dropdown List From SelectList - c#

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

Related

How to use #Html.DropDownList by giving values manually? [duplicate]

This question already has answers here:
Bind Html.DropDownList with static items
(6 answers)
Closed 5 years ago.
I want to use #Html.DropDownList without any model but simply as we use select in normal html.
Please revert, Thanks!
Its very simple, u may understand we the following example.
#Html.DropDownList("selectedState", new List<SelectListItem>
{
new SelectListItem {Text = "Not verified", Value = "1"},
new SelectListItem {Text = "Verified", Value = "2"},
new SelectListItem {Text = "Migrated", Value = "3"}
new SelectListItem {Text = "Completed", Value = "4"}
}, "All states", new { #onchange = "form.submit();", #class = "form-control" })
You can use #Html.Dropdownlist without model
for example in controller you set the values for Dropdownlist,
var dates = new List<SelectListItem>{
new SelectListItem {Selected = false, Text = "Show offers for all dates", Value = ""},
new SelectListItem {Selected = false, Text = "Show offers for today", Value = today.ToShortDateString()},
new SelectListItem {Selected = false, Text = "Show offers for this week", Value = endOfThisWeek.ToShortDateString()},
new SelectListItem {Selected = false, Text = "Show offers for this month", Value = endOfThisMonth.ToShortDateString()},
new SelectListItem {Selected = false, Text = "Show offers for further out", Value = all.ToShortDateString()},};
ViewBag.Dropdowndata = dates;
and you can access the values of Viewbag from View and set it to Dropdown list like
#using (Html.BeginForm())
{
<label>
Select Dates</label>
#Html.DropDownList("Dates", (IEnumerable<SelectListItem>)ViewBag.Dropdowndata, "---Select---", new { id = "dateList" ,#class = "form-control" });
}

DropDownFor and bool? not working

I use MVC and have a property with bool?.
I want to use a dropdown box for this, so my Model has a List like this:
var YesOrNoTriState = new List<SelectListItem> {
new SelectListItem { Text = "Select", Value = "" },
new SelectListItem { Text = "Yes", Value = true.ToString() },
new SelectListItem { Text = "No", Value = false.ToString() }
};
My model is null, so it has no value but true will be selected...
Here is my Razor Code:
#Html.DropDownListFor(
x => x.MoProVerglasung,
Model.MoProVerglasungDropDown,
new { #class = "form-control" })

How to selected value true in dropdownlist MVC

i have problem in dropdownlist selected value.
View
#Html.DropDownList("QuestionType", (IEnumerable<SelectListItem>)ViewData["questiontype"], new { id = "QuestionType", #style = "max-width: 200px;width: 200px", #OnChange = "HideForm(this)", #class = "form-control" })
Controller
var questionTypeList = new SelectList(
new List<SelectListItem>
{
new SelectListItem { Value = "1", Text = "Automatic", Selected = false },
new SelectListItem { Value = "2", Text = "Custom", Selected = true}
}, "Value", "Text"
).ToList();
var questionType = new SelectList(questionTypeList, "Value", "Text");
ViewData["questiontype"] = questionType;
i want value=2 is selected true in view but my script above is not working, how can i solve this problem?
i have modified my code. i'm not using stronglytype which bind to dropdownlist. i'm using viewdata. this is my code:
Controller
List<SelectListItem> questionTypeList = new List<SelectListItem>();
questionTypeList.Add(new SelectListItem() { Text = "Automatic", Value = "1" });
questionTypeList.Add(new SelectListItem() { Selected = true, Text = "Custom", Value = "2" });
ViewData["questiontype"] = questionTypeList;
View
#Html.DropDownList("QuestionType", ViewData["questiontype"] as SelectList, new { id = "QuestionType", #style = "max-width: 200px;width: 200px", #OnChange = "HideForm(this)", #class = "form-control" })
why this code work and why previous code not work? i'm so confuse...
Not sure if you have a strongly typed view but you can use
DropdownlistFor(model=>model.QuestionType, selectlistItem)
then in your controller set
model.QuestionType to 2;
then
return View(model);

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)

How to make a select list item selected in asp.net mvc?

I have the following code but it never selects the value I want.
List<SelectListItem> list = new List<SelectListItem>();
SelectListItem one = new SelectListItem() { Text = "MyTest", Value = "MyTest"};
SelectListItem two= new SelectListItem() { Text = "Test2", Value = "Test2" };
if (id == "MyTest")
{
one .Selected = true;
}
else
{
two.Selected = true;
}
list.Add(one);
list.Add(two);
ViewData["DDL"] = new SelectList(list, "value", "text");
So I am not sure what I am doing wrong
in my view I have
<%= Html.DropDownList("DDL") %>
You should use:
ViewData["DDL"] = new SelectList(list, "value", "text", id == "MyTest" ? "MyTest" : "Test2");
You should define selected value in SelectList constructor.
EDIT
Answer to question:
You don't have to provide List to SelectList constructor. It can be collection of any object. You just have to provide key, value propery and selected value. Your code could also look like:
var selectItems = new Dictionary<string, string> {{"MyTest", "MyTest"}, {"Test2", "Test2"}};
ViewData["DDL"] = new SelectList(selectItems, "Key", "Value", id == "MyTest" ? "MyTest" : "Test2");

Categories