Multiple selction in Dropdownlist of asp.net MVC 3 - asp.net

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.

Related

How to set a default value in a DropDownListFor

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

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 ))

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

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

MVC Drop Down List

This construction below using dropdownlist does not work!!
<% = Html.DropDownList (ddlUf, "All", New With (. Class = "text"})%>
It only works if I do this:
<% = Html.DropDownList (ddlUf, "All")%>
Or this:
<% = Html.DropDownList (ddlUf, Nothing, New With (. Class = "text"})%>
How do I solve this problem?
Thanks
use new{ #class = "text"})
I think you have the order of parameters mixed up. Assuming that ddlUf is a string with the DropDownList name, and "All" is supposed to be the default option, then you need something like this:
<% =Html.DropDownList(ddlUf, Model.FullListOfSelectListItems, "All", New With (. Class = "text") %>
There's some parameter order/validity issues here. The Html.DropDownList() method works by taking the following:
string name - assigns a name/id to the control
SelectList selectList - the list of options to appear in the drop down. You can construct this by creating a List and then using Linq to select the items from the list you want to appear in the drop down i.e:
List<string> myList = new List<string>();
//Add items to appear in the drop down.
myList.Add("Item1");
myList.Add("AnotherItem");
...
//Select all the items from the list and place them into a SelectList object.
SelectList dropDownList = new SelectList(from items in myList select items);
string optionLabel - the text for a default, empty item.
object htmlAttributes - a selection of HTML attributes to apply to the control.
So in your example you might want to go for something like:
#Html.DropDownList("MyDropDown", Model.MyConstructedSelectList, "Default item", new { #class = "text" })
For more information on using drop down lists with models in MVC, see this blog post:
http://277hz.co.uk/Blog/Show/10/drop-down-lists-in-mvc--asp-net-

Resources