In ASP.NET MVC 2, I'd like to write a very simple dropdown list which gives static options. For example I'd like to provide choices between "Red", "Blue", and "Green".
See this MSDN article and an example usage here on Stack Overflow.
Let's say that you have the following Linq/POCO class:
public class Color
{
public int ColorId { get; set; }
public string Name { get; set; }
}
And let's say that you have the following model:
public class PageModel
{
public int MyColorId { get; set; }
}
And, finally, let's say that you have the following list of colors. They could come from a Linq query, from a static list, etc.:
public static IEnumerable<Color> Colors = new List<Color> {
new Color {
ColorId = 1,
Name = "Red"
},
new Color {
ColorId = 2,
Name = "Blue"
}
};
In your view, you can create a drop down list like so:
<%= Html.DropDownListFor(n => n.MyColorId,
new SelectList(Colors, "ColorId", "Name")) %>
<%:
Html.DropDownListFor(
model => model.Color,
new SelectList(
new List<Object>{
new { value = 0 , text = "Red" },
new { value = 1 , text = "Blue" },
new { value = 2 , text = "Green"}
},
"value",
"text",
Model.Color
)
)
%>
or you can write no classes, put something like this directly to the view.
Avoid of lot of fat fingering by starting with a Dictionary in the Model
namespace EzPL8.Models
{
public class MyEggs
{
public Dictionary<int, string> Egg { get; set; }
public MyEggs()
{
Egg = new Dictionary<int, string>()
{
{ 0, "No Preference"},
{ 1, "I hate eggs"},
{ 2, "Over Easy"},
{ 3, "Sunny Side Up"},
{ 4, "Scrambled"},
{ 5, "Hard Boiled"},
{ 6, "Eggs Benedict"}
};
}
}
In the View convert it to a list for display
#Html.DropDownListFor(m => m.Egg.Keys,
new SelectList(
Model.Egg,
"Key",
"Value"))
Hi here is how i did it in one Project :
#Html.DropDownListFor(model => model.MyOption,
new List<SelectListItem> {
new SelectListItem { Value = "0" , Text = "Option A" },
new SelectListItem { Value = "1" , Text = "Option B" },
new SelectListItem { Value = "2" , Text = "Option C" }
},
new { #class="myselect"})
I hope it helps Somebody. Thanks
Or if it's from a database context you can use
#Html.DropDownListFor(model => model.MyOption, db.MyOptions.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }))
With "Please select one Item"
#Html.DropDownListFor(model => model.ContentManagement_Send_Section,
new List<SelectListItem> { new SelectListItem { Value = "0", Text = "Plese Select one Item" } }
.Concat(db.NameOfPaperSections.Select(x => new SelectListItem { Text = x.NameOfPaperSection, Value = x.PaperSectionID.ToString() })),
new { #class = "myselect" })
Derived from the codes: Master Programmer && Joel Wahlund ;
King Reference : https://stackoverflow.com/a/1528193/1395101 JaredPar ;
Thanks Master Programmer && Joel Wahlund && JaredPar ;
Good luck friends.
#using (Html.BeginForm()) {
<p>Do you like pizza?
#Html.DropDownListFor(x => x.likesPizza, new[] {
new SelectListItem() {Text = "Yes", Value = bool.TrueString},
new SelectListItem() {Text = "No", Value = bool.FalseString}
}, "Choose an option")
</p>
<input type = "submit" value = "Submit my answer" />
}
I think this answer is similar to Berat's, in that you put all the code for your DropDownList directly in the view. But I think this is an efficient way of creating a y/n (boolean) drop down list, so I wanted to share it.
Some notes for beginners:
Don't worry about what 'x' is called - it is created here, for the
first time, and doesn't link to anything else anywhere else in the
MVC app, so you can call it what you want - 'x', 'model', 'm' etc.
The placeholder that users will see in the dropdown list is "Choose an option", so you can change this if you want.
There's a bit of text preceding the drop down which says "Do you like pizza?"
This should be complete text for a form, including a submit button, I think
Hope this helps someone,
Related
i´m struggling a long time with this problem.
I want the value of my selectListItem to use it in the controller to make the right API call.
Thats my Code in razor:
var selectList = new SelectList(
new List<SelectListItem>
{
new SelectListItem {Text = "Borussia Dortmund", Value = "10303", Selected= false},
new SelectListItem {Text = "FC Bayern München", Value = "10285", Selected= false},
new SelectListItem {Text = "Bayer 04 Leverkusen", Value = "10281", Selected= false},
.
.
.
}, "Value", "Text", 1);
#Html.DropDownList("ddlChosenTeam", selectList, "Team wählen", new { #class = "css-class" })
}
If i try the following in my Controller, it don´t know the selectList:
protected void SquadChosen_Click(object sender, EventArgs e)
{
int selectedSquad = selectList.SelectedValue;
}
I just want to pick the value like 10303 if "borussia Dortmund" is selected, please safe my time.
Edit:
I wrote some other Code that is maybe more what i need.
my Controller now:
public SelectList UserChosenSquad()
{
var ssl = new SelectList(new List<SelectListItem>
{
new SelectListItem {Text = "Borussia Dortmund", Value = "10303", Selected = false},
new SelectListItem {Text = "FC Bayern München", Value = "10285", Selected = false},
new SelectListItem {Text = "Bayer 04 Leverkusen", Value = "10281", Selected = false},
}, "Value", "Text");
return ssl;
}
The Model:
public class ChosenSquad
{
public string Text { get; set; }
public string Value { get; set; }
public bool Selected { get; set; }
}
now i struggle with the view
#model ChosenSquad
#{
#Html.DropDownListFor(model => model.Text, Model.SelectListItem, "Text", "-Team wählen-")
Is this the right way ?
I need to show the DropDownList and then the value like before, i first want to see my list and then perhaps get the value with an if method that looks for selected item, right!?
Although I don't agree with how you're creating this dropdown as you shouldn't really be creating and defining new variables inside the view. To pass the data from the view to the controller you should have an onchange event on the drop down that calls a javascript function.
#Html.DropDownList("ddlChosenTeam", selectList, "Team wählen", new { #class = "css-class", onchange="javascript:sendToController(this.value)" })
and the javascript function should look a bit like this:
function sendToController(value)
{
var json = '{value: ' + value + '}';
$.ajax({
url:'#Url.Action('method','controller')',
type: 'POST',
data: json,
contentType:'Application/json',
success:function(result){
//whatever you're doing next
}
});
}
Got it. I just edited my List like this:
public List<SelectListItem> ChosenSquad()
{
var ssl = new List<SelectListItem>
{
new SelectListItem {Text = "Borussia Dortmund", Value = "10303", Selected = false},
new SelectListItem {Text = "FC Bayern München", Value = "10285", Selected = false},
new SelectListItem {Text = "Bayer 04 Leverkusen", Value = "10281", Selected = false},
return ssl;
}
and in my view i got the following:
<select id=SquadSelectList asp-items="#((List<SelectListItem>)ViewData["Teams"])"></select>
now it renders the List and i just have to get the Value out of it when selected, help would be great but the most important thing is done.
This question already has answers here:
MVC5 - How to set "selectedValue" in DropDownListFor Html helper
(5 answers)
Closed 5 years ago.
I have a IEnumerable<SelectListItem>
My ViewModel
public class StatusClass
{
public string Status { get; set; }
public IEnumerable<SelectListItem> StatusList { get; set; }
}
I set values in to StatusList from my controller.
StatusClass statusObj = new CRM.StatusClass();
List<SelectListItem> Discountdata = new List<SelectListItem>();
Discountdata.Add(new SelectListItem() { Value = "All", Text = "All" });
Discountdata.Add(new SelectListItem() { Value = "Draft", Text = "Draft" });
Discountdata.Add(new SelectListItem() { Value = "Issued", Text = "Issued" });
Discountdata.Add(new SelectListItem() { Value = "Partial", Text = "Partially Received" });
Discountdata.Add(new SelectListItem() { Value = "Received", Text = "Received" });
Discountdata.Add(new SelectListItem() { Value = "PAID", Text = "Paid" });
Discountdata.Add(new SelectListItem() { Value = "Billed", Text = "Billed" });
statusObj.StatusList = new SelectList(Discountdata, "Value", "Text");
This works fine and my HTML is like this:
#Html.DropDownListFor(model => model.Status, Model.StatusList)
What i want is, I need to set the selected value from the controller when the list get created.
Suppose I have a string like this:
string newwStatus = "Issued";
How can I set it as selected in the SelectListItem.
I tried this, but its not working in my case:
foreach(var item in StatusList)
{
if(item.value == status)
{
item.Selected = true;
}
}
and tries this too:
IEnumerable<SelectListItem> selectList =
from s in StatusList
select new SelectListItem
{
Selected = (s.Value == status),
Text = s.Text,
Value = s.Value
};
I dont know if these are the right way if someone know how to do this, please help.
Thanks in advance.
The Selected property of SelectListItem is ignored when binding to a model property. You need to set the value of your Status property in the GET method before you pass the model to the view
List<SelectListItem> Discountdata = new List<SelectListItem>
{
new SelectListItem() { Value = "All", Text = "All" },
new SelectListItem() { Value = "Draft", Text = "Draft" },
new SelectListItem() { Value = "Issued", Text = "Issued" },
....
};
StatusClass model = new CRM.StatusClass
{
StatusList = Discountdata,
Status = "Issued"
};
return View(model);
and the 2nd option in your <select> element will be selected.
Note that Discountdata is already IEnumerable<SelectListItem> and using new SelectList(Discountdata, "Value", "Text") to create an identical IEnumerable<SelectListItem> is unnecessary extra overhead.
Note also that since you have the same value for both the value attribute and display text, you could simply use
List<string> Discountdata = new List<string>{ "All", "Draft", "Issued", ... };
and in the model constructor
StatusList = new SelectList(Discountdata),
You're binding Status property to the dropdown. So set the value either from database, or in your case, a default value "Issued" like this:
statusObj.Status = "Issued"
I have a class like this:
public class MyClass
{
public SelectList saleRange = new SelectList(new[]
{
new SelectListItem { Selected = true ,Text = "--- Select date range ---", Value = "0" },
new SelectListItem { Selected = false, Text = "7 days", Value = "7" },
new SelectListItem { Selected = false, Text = "14 days", Value = "14" },
new SelectListItem { Selected = false, Text = "21 days", Value = "21" },
new SelectListItem { Selected = false, Text = "30 days", Value = "30" },
}, "Value", "Text");
}
My action:
public ActionResult Index()
{
var model = new MyClass();
return View(model);
}
And the view looks like this:
#Html.DropDownListFor(m => m.saleRange, (IEnumerable<SelectListItem>)Model.saleRange,new { #class= "select2" , #style = "width:95%;border-left:2px solid #eee" })
But I'm getting this error:
Unable to cast object of type 'ServiceStack.Html.SelectList' to type 'System.Collections.Generic.IEnumerable`1[System.Web.Mvc.SelectListItem]'.
What am I doing wrong here? How can I populate the dropdownlist from my viewmodel with hardcoded values??
Change your model to the following (note that the SelectList class needs to be from namespace System.Web.Mvc, not ServiceStack):
public class MyClass
{
//You need somewhere to put the sales range thats selected
public string SelectedSalesRange { get; set; }
public System.Web.Mvc.SelectList SaleRange = new System.Web.Mvc.SelectList(new[]
{
//Note that I have removed the "Default" item
//And the Selected=False (since the default value of a bool is false)
new System.Web.Mvc.SelectListItem { Text = "7 days", Value = "7" },
new System.Web.Mvc.SelectListItem {Text = "14 days", Value = "14" },
new System.Web.Mvc.SelectListItem { Text = "21 days", Value = "21" },
new System.Web.Mvc.SelectListItem { Text = "30 days", Value = "30" },
}, "Value", "Text");
}
And change your view to:
#Html.DropDownListFor(model => model.SelectedSalesRange, SaleRange, "--- Select date range ---")
If you want to use ServiceStack, then the entire nature of your question is invalid and you need to edit or ask a new question. You have only asked about MVC5
SelectList is not the same thing as IEnumerable<SelectListItem>, so there's no way to cast it to that. You could cast saleRange.Items, as that property of SelectList is in fact an IEnumerable<SelectListItem>.
However, that's completely unnecessary in the first place. As saleRange is a property on your model, it is strongly typed and you don't need to cast it to anything. SelectList is already a valid type to pass there, so just use saleRange directly.
I am using MVC 5.
I have my ViewBag for list as
ViewBag.TitleList = new SelectList((new string[] { "Mr", "Miss", "Ms", "Mrs" }), contact.Title);
//contact.Title has selected value.
then I tried converting the array to SelectListItem ( to no avail)
On the View it looks like
#Html.DropDownListFor(model => model.Title, ViewBag.TitleList as SelectList, "Select")
also I tried
#Html.DropDownList("Title", ViewBag.TitleList as SelectList, "Select")
The list loads successfully but the Selected Value is Not selected.
How to Fix this problem?
Update
The culprit was ViewBag.Title matching my model.Title. Renamed my model property to something else and it worked. Arrgh!
Set value of the Title property in the controller:
ViewBag.TitleList = new SelectList(new string[] { "Mr", "Miss", "Ms", "Mrs" });
viewModel.Title = "Miss"; // Miss will be selected by default
Another possible reason (and the correct one, based on the comments below) is that ViewData["Title"] is overridden by another value. Change name of the Title property to any other and everything should work.
When a value is not specified (i.e. "Id"), DropDownListFor sometimes does not behave properly. Try this:
public class FooModel
{
public int Id { get; set; }
public string Text { get; set; }
}
var temp = new FooModel[]
{
new FooModel {Id = 1, Text = "Mr"}, new FooModel {Id = 2, Text = "Miss"},
new FooModel {Id = 3, Text = "Ms"}, new FooModel {Id = 4, Text = "Mrs"}
};
ViewBag.TitleList = new SelectList(temp, "Id", "Text", 2);
EDIT: other sololution
var temp = new []
{
new SelectListItem {Value = "Mr", Text = "Mr"}, new SelectListItem {Value = "Miss", Text = "Miss"},
new SelectListItem {Value = "Ms", Text = "Ms"}, new SelectListItem {Value = "Mrs", Text = "Mrs"}
};
ViewBag.TitleList = new SelectList(temp, "Value", "Text", "Miss");
Please let me know how can I set the selected value in the chosen multiselect dropdownlist. I have tried everything available on net but nothing is working.
My view is
#Html.DropDownListFor(
model => model.SelectedSkills,
new SelectList(
Model.SkillList,
"Value",
"Text",
Model.SelectedSkills
),
new {
#class = "chosen",
id = "ddlSkill",
name="ddlPersonSkill",
#tabindex = "4",
multiple = "true"
}
)
#Html.HiddenFor(
model => model.SelectedSkills,
new { id = "hdnPersonSkill" }
)
Now in page load I need to display the selected value :
var personskill = $("#hdnPersonSkill").val();
$('#ddlSkill option:nth-child(3)').attr('selected', 'selected');
$('#ddlSkill').trigger('liszt:updated');
But above code is not working
CHHTML:
#Html.ListBoxFor(
model => model.SelectedSkills,
new SelectList(
Model.SkillList,
"Value",
"Text",
Model.SelectedSkills
),
new
{
#class = "chosen",
id = "ddlSkill",
name = "ddlPersonSkill",
#tabindex = "4",
multiple = "true"
}
)
Javascript to show all selected:
$(document).ready(function () {
var conceptName = $('#ddlSkill').find(":selected").text();
alert(conceptName);
});
Model jsut for example:
public string[] SelectedSkills { get; set; }
public IEnumerable<SelectListItem> SkillList { get; set; }
public MyModel()
{
SkillList = new List<SelectListItem>();
((List<SelectListItem>)SkillList).Add(new SelectListItem { Text = "Skill 1", Value = "1" });
((List<SelectListItem>)SkillList).Add(new SelectListItem { Text = "Skill 2", Value = "2" });
((List<SelectListItem>)SkillList).Add(new SelectListItem { Text = "Skill 3", Value = "3" });
((List<SelectListItem>)SkillList).Add(new SelectListItem { Text = "Skill 4", Value = "4" });
SelectedSkills = new string[3];
SelectedSkills[0] = "1";
SelectedSkills[1] = "2";
SelectedSkills[2] = "3";
}