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.
Related
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");
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");