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"
Related
I have a selectListItem in a controller that I use to populate a dropdownlist.
public List<SelectListItem> BankSelectList()
{
List<SelectListItem> Region = new List<SelectListItem>()
{
new SelectListItem { Text = "" , Value = "",Selected = true},
new SelectListItem { Text = "North" , Value = "North"},
new SelectListItem { Text = "East" , Value = "East"},
new SelectListItem { Text = "North East" , Value = "North East"},
new SelectListItem { Text = "West" , Value = "West"},
};
return bank;
}
Is there a way I can reuse this in a different controller without needing to declare the list again in the other controller? I dont want to go to each controllers to update in case there are any changes in the future. I dont put it in database because the probability of changes are low, and Im also trying to save on performace.
Use the static class :
public static class DataStaticSelectList
{
public static List<SelectListItem> BankSelectList()
{
List<SelectListItem> Region = new List<SelectListItem>()
{
new SelectListItem { Text = "" , Value = "",Selected = true},
new SelectListItem { Text = "North" , Value = "North"},
new SelectListItem { Text = "East" , Value = "East"},
new SelectListItem { Text = "North East" , Value = "North East"},
new SelectListItem { Text = "West" , Value = "West"},
};
return bank;
}
}
And in your Controller to access the data :
var selectList = DataStaticSelectList.BankSelectList() ;
As mentioned above a static class could work.
You could also make a seperate class that provides you with the required SelectListItem collection via a specific method. This potentially opens the option to use DI and populate the contents via whatever dataset your using.
public List<SelectListItem> GetBankSelectList()
{
return new List<SelectListItem>()
{
new SelectListItem { Text = "" , Value = "",Selected = true},
new SelectListItem { Text = "North" , Value = "North"},
new SelectListItem { Text = "East" , Value = "East"},
new SelectListItem { Text = "North East" , Value = "North East"},
new SelectListItem { Text = "West" , Value = "West"},
};
}
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.
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");
I am not able to identify why DropDownListFor is not selecting the correct option. Below is my code, I have hard-coded 'Selected' values for testing but still when page loads I am getting 'Select Country' as selected value.
#Html.DropDownListFor(x => x.CountryID,
new List<SelectListItem> {
new SelectListItem { Text = "USA", Value = "US", Selected = false},
new SelectListItem { Text = "UK", Value = "UK", Selected = true},
new SelectListItem { Text = "Australia", Value = "AUS", Selected = false }
},"Select Country")
But, same is working fine for DropDownList!
#Html.DropDownList("CountryID",
new List<SelectListItem> {
new SelectListItem { Text = "USA", Value = "US", Selected = false},
new SelectListItem { Text = "UK", Value = "UK", Selected = true},
new SelectListItem { Text = "Australia", Value = "AUS", Selected = false }
},"Select Country")
Please Help.
The selected option will be based on the actual value of property CountryID when you use the strongly type helper. So if you set CountryID="UK" in the controller before you pass the model to the view, then the second option will be selected.
Try the following:
#{
var listItems = new List<SelectListItem>
{
new SelectListItem { Text = "USA", Value = "USA" },
new SelectListItem { Text = "UK", Value = "UK", Selected = true },
new SelectListItem { Text = "Australia", Value = "AUS" }
};
}
#Html.DropDownListFor(x => x.CountryID, listItems, "-- Select Country --")
View (RelacionamentoConvidado.cshtml)
#Html.DropDownList("Foi_Emitido", (IEnumerable<SelectListItem>)ViewBag.Foi_Emitido, #SRSVP.Util.Constante.HTML_HELPER_DROPDOWN_EMPTY_VALUE, new { #class = "input-small" })
Controller (EventoConvidadoController)
ViewBag.Foi_Emitido = new SelectList(Common.SimNao(model.foi_emitido), "Value", "Text");
Common.cs (Static Class)
public static List<SelectListItem> SimNao(object selectedItem)
{
List<SelectListItem> _returnList = new List<SelectListItem>();
SelectListItem _mList = new SelectListItem();
_mList = new SelectListItem() { Text = "Sim", Value = "true", Selected = selectedItem == null ? false : selectedItem.ToString().Equals("true") };
_returnList.Add(_mList);
_mList = new SelectListItem() { Text = "Não", Value = "false", Selected = selectedItem == null ? false : selectedItem.ToString().Equals("false") };
_returnList.Add(_mList);
return _returnList;
}
When the page is loaded select item is not select item that return from my database.
How can I do this?
This Often happens when the Select List and bound variable share the same name --Foi_Emitido. Try renaming the ViewBag SelectList
#Html.DropDownList("Foi_Emitido", (IEnumerable<SelectListItem>)ViewBag.Foi_Emitido_SelectList, #SRSVP.Util.Constante.HTML_HELPER_DROPDOWN_EMPTY_VALUE, new { #class = "input-small" })
Controller (EventoConvidadoController)
ViewBag.Foi_Emitido_SelectList= new SelectList(Common.SimNao(model.foi_emitido), "Value", "Text");