How to set a default value in a DropDownListFor - asp.net

I've been working on this for 2 days and I can't make it work. I'm trying to make a DropDownListFor with a default value (Like in an Edit page). I made it work without a model but when there is a model, it shows the first item as the default not the one I wanted.
I tried adding a Selected = true in a SelectListItem while being in a foreach loop like this, still not working:
List<SelectListItem> selectListCategories = new List<SelectListItem>();
foreach(var item in listCategories)
{
if(item.Id == Model.Category.Id)
{
selectListCategories.Add(new SelectListItem { Value = item.Id.ToString(), Text = item.Name, Selected=true });
}
else
{
selectListCategories.Add(new SelectListItem { Value = item.Id.ToString(), Text = item.Name });
}
}
This one worked but without a model.
I also tried adding a default value in the SelectList object like that :
#Html.DropDownListFor(model => model.Category, new SelectList(ViewBag.ListingCategories, "Id", "Name", Model.Category.Id))
It either didn't work or there is something I didn't understand correctly because I tried adapting some example I saw here and on msdn posts without any success.
ViewBag.ListingCategories contains a IEnumerable list of my categories taken from my database.
Of course, Model.Category contains a Category object with an Id (this is a Foreign Key to another table) and a Name.
Now I'm out of option so hopefully I can find help here.
Thanks.

See this answer (by #Elad Lachmi):
SelectListItem has a Selected property. If you are creating the
SelectListItems dynamiclly, you can just set the one you want as
Selected = true and it will be the default.
SelectListItem defaultItem = new SelectListItem()
{
Value = 1,
Text = "Deafult Item",
Selected = true
};

Related

HTML Select control does not have selected value when generated with Razor DropDownListFor

I have a view in asp.net/mvc4/razor application where I want to edit value of model using dropdownlist control. I use it this way:
#Html.DropDownListFor(m => m.DateFormat, new SelectList(new [] {"mm/dd/yyyy", "dd/mm/yyyy"}))
The value of DateFormat property is set to one of those values in model but when I load the view, the html select is always set to first value. Am i missing sth?
UPDATE:
This was driving me nuts for two days. Finally I changed the name of property and it started to work. I think it somehow conflicted with value I stored in ViewData/ViewBag collection under the same key. I am not yet sure why. Maybe somebody can explain that?
Try your SelectList something like this where you define the text and the value, along with the selected item.
#(Html.DropDownListFor(m => m.DateFormat, new SelectList
(
new List<Object> {
new {
value = "mm/dd/yyyy", text = "mm/dd/yyyy"
},
new {
value = "dd/mm/yyyy", text = "dd/mm/yyyy"
}
}, "value", "text", Model.DateFormat)
))
This code is untested
Make the SelectList a buddy property of the model.
public class MyModel(){
prop DateTime MyDate {get;set;};
prop SelectList SelectDates {get;set;}
}
Then populate the SelectList after you have selected your date (remember to do this every time you build your model):
SelectDates = dates.Select(d => new SelectListItem
{
Value = d.ToString(),
Text = d.ToString(),
Selected = d == MyDate
})
Then use the property when you build your dropdown:
#Html.DropDownListFor(m => m.DateFormat, Model.SelectDates ))

Creating custom text value for ListBoxFor

So my initial need is that I need to display two properties in the MVC control ListBoxFor. Basically I want to do something like this:
#Html.ListBoxFor(m => m.ContractLocations, new SelectList(Model.ContractLocations, "CUSTNMBR", "CUSTNAME" + " - " + "CUSTNMBR" ), new { #class = "form-control row marb10", size = 15 })
But obviously it won't let me do that. So I am assuming that I need to create a custom property in my ViewModel? But I'm not really sure how to combine two strings within my model? Basically I want to create something similar to a ko.computed where it adds the two values together and then I can display it on my ListBox control. Although I might be thinking about this all wrong and maybe there is an easier alternative?
So what is the best option to accomplish this?
Add a list property to your model:
public IEnumerable<SelectListItem> ContractLocationsList { get; set; }
In your Action, build your list, something like:
myModel.ContractLocationsList = new List<SelectListItem>() {
new SelectListItem() { Value = Customer.Id, Text = Customer.Name + " - " + Customer.Number }
};
And now in your View, you can simply:
#Html.ListBoxFor(m => m.ContractLocations, Model.ContractLocationsList, ...)
Notice that ContractLocationsList holds the list of values to select from, while ContractLocations holds the actual selected values.

How to use the HTML Helper of Listbox?

I am trying to create a simple Listbox, utilising HTML Helpers and I can't find any resource that guides me through this.
<%= Html.ListBox("listbox_name") %>
And it asks for IEnumerable(SelectListItem) and I dont know how to create one and pass it.
Please help me
Depends on how you want to provide the data for the listbox. If it is static data, you could simply declare a List<SelectListItem> in the view and pass that in:
var mySelectItems = new List<SelectListItem> {
new SelectListItem { Text = "First item", Value = "1" },
new SelectListItem { Text = "Second item", Value = "2" }
};
...
Html.ListBox("listbox_name", mySelectItems)
Otherwise, just get the data from whereever you get it, and pass it in with the model

Multiple selction in Dropdownlist of asp.net MVC 3

Can we select multiple items from razor dropdownlist control. i.e for
#Html.DropDownListFor(m=>m.Country, CountryList as SelectList,"--Select--")
You can try maybe something like this ...
#Html.ListBoxFor(m=>m.Country, new MultiSelectList(CountryList as SelectList, "CountryID", "Select"))
You just have to add a new { "multiple" = "multiple" } as last Parameter of the function - this will render a multiselect.
Given a list of Items (in this example with fields Id and Name), you can start with a List of SelectListItem as follows:
List<SelectListItem> Choices = Items.Select(x => new SelectListItem { Value = Convert.ToString(x.Id).Trim(), Text = x.Name }).ToList();
#Html.ListBox("ListBoxIds", new MultiSelectList(Choices, "Value", "Text"))
In the controller, you will get ListBoxIds as a list of selected Ids.

ASP.Net MVC dropdown selected value

I have been dealing with the dropdownlist which i am able to populate but if i come back to edit a record, the dropdown is not showing the selected value.....
In controller,
var datacontext = new ServicesDataContext();
var serviceToUpdate = datacontext.Mapings.First(m => m.CustomerServiceMappingID == id);
var qw = (from m in datacontext.Mapings
where id == m.CustomerServiceMappingID
select m.CustomerID).First();
ViewData["CustomerID"] = qw;
int b = Convert.ToInt32(serviceToUpdate.ServiceID);
var a = datacontext.services.Select(arg => arg.ServiceID).ToList();
ViewData["ServiceID"] = new SelectList(a,serviceToUpdate.ServiceID);
In view:
#Html.DropDownListFor(model => model.ServiceID, ViewData["ServiceID"] as SelectList)
serviceToUpdate,ServiceID has the right value but somehow when I try to edit the selected value is not returned... instead the first value of dropdown is only returned...
I had the same problem. Use the null object pattern where you have a reserved id and the display name of the item is "please choose..." or something similar. Before passing in the model to the view, append to the beginning of the collection the null object. In the controller on the way back in, test for it. You can then set the property to null if the person didn't choose anything.
Here is my question:
DropDownListFor Not Displaying/Persisting Null for First Choice in List
You shouldn't have to use view data explicitly either like you are doing.
Code in Controller:
ViewBag.Services = new SelectList(a, "ServiceId", "#Servicename");
ServiceId is the property representing the key-value for the item displayed in the dropdown list
#Servicename stands for the property representing the text you want to display for the item in the dropdownlist)
Code in View:
#using(#BeginForm){
SelectList services = Viewbag.Services;
#Html.DropDownListFor(model => model.ServiceID, services)
}

Resources