Rectangle 27 88

Here's an example illustrating the strongly typed version:

public class MyViewModel
{
    public int[] SelectedItemIds { get; set; }
    public MultiSelectList Items { get; set; }
}
public class HomeController : Controller
{
    public ActionResult Index()
    {
        // Preselect items with id 1 and 3
        var selectedItemIds = new[] { 1, 3 };

        var model = new MyViewModel
        {
            Items = new MultiSelectList(
                new[] 
                {
                    // TODO: Fetch from your repository
                    new { Id = 1, Name = "item 1" },
                    new { Id = 2, Name = "item 2" },
                    new { Id = 3, Name = "item 3" },
                }, 
                "Id", 
                "Name", 
                selectedItemIds
            )
        };

        return View(model);
    }
}
<%: Html.ListBoxFor(x => x.SelectedItemIds, Model.Items) %>

ty! this helped me out a bunch.

You are the man! :D Thank you for helping with such good and clean samples of code throughout StackOverflow. God bless your life!

asp.net mvc - Challenges with selecting values in ListBoxFor - Stack O...

asp.net-mvc asp.net-mvc-2
Rectangle 27 8

I don't know if this behaviour has changed in the RTM of MVC3 that I'm using, but it seems that selection and binding now works out of the box. The only catch is that the model should contain a property with the IDs, like that :

public class MyViewModel {
    public int[] ItemIDs { get; set; }
}

Then the following in the view would work fine, both pre-selecting the correct values and binding correctly during post:

@Html.ListBoxFor(model => model.ItemIDs, (IEnumerable<SelectListItem>)(new[] { 
                                new SelectListItem() { Value = "1", Text = "1" }, 
                                new SelectListItem() { Value = "2", Text = "2" } 
                             }))

A small correction. Even though the above works, there seems to be some minor bug that could cause problems. It seems that when the ViewBag contains a property named "X" and the property of the model is also named "X" the automatic selection for the ListBox does not work... Strange things...

Still in 2016 this comments is helping me - I had a ViewBag property with the same name as the bound model Property, so the selected items population didnt work.

asp.net mvc - Challenges with selecting values in ListBoxFor - Stack O...

asp.net-mvc asp.net-mvc-2
Rectangle 27 2

@Html.ListBoxFor(
    model => model.Roles, 
    new MultiSelectList(db.Roles, "Id", "Name")
)
@Html.ValidationMessageFor(model => model.Roles)

Doesn't work.., never ever any option is selected, until:

public ActionResult Edit(int id)
{
    var user = db.Users.Find(id);
    // this is workaround for http://aspnet.codeplex.com/workitem/4932?ProjectName=aspnet
    ViewData["Roles"] = user.Roles.Select(r => r.Id);
    return View(user);
}

Probably obvious (but still nice to know): this also works if you use the MVC3-style ViewBag.Roles.

Helps even in MVC5 . Whyyyy this works?

asp.net mvc - Challenges with selecting values in ListBoxFor - Stack O...

asp.net-mvc asp.net-mvc-2
Rectangle 27 3

The expression you are passing for the selected values needs to be IEnumerable because ListBoxFor supports multiple selected items.

thats right.. if you only want to have an single int/id then you should use DropDownListFor instead

asp.net mvc - MVC ListBoxFor raises "value cannot be null" exception -...

asp.net-mvc asp.net-mvc-2
Rectangle 27 3

The expression you are passing for the selected values needs to be IEnumerable because ListBoxFor supports multiple selected items.

thats right.. if you only want to have an single int/id then you should use DropDownListFor instead

asp.net mvc - MVC ListBoxFor raises "value cannot be null" exception -...

asp.net-mvc asp.net-mvc-2
Rectangle 27 1

Inside your HttpPost action you cannot expect the AvailalableEmployee and SelectedEmployee collections to be populated. That's due to the nature of how HTML works. Only the selected values are sent to the server when you submit the form. The text values of the select fields are never sent to your server when you submit the form.

So all you can hope of getting populated inside this HttpPost action is the AvailableEmpCodeArray and the SelectedEmpCodeArray collections. They will contain the values of the selected items in the corresponding select fields. Notice that I have bolded selected. This means that only if you select any items in the corresponding boxes those collections will be bound. If you don't select anything, they will remain null and that's perfectly normal.

Here's an example of the user that has selected nothing. He just used the << and >> buttons to toggle the values between the lists, but please notice how absolutely nothing is selected:

Notice how nothing is selected? So that's all you will get in your controller action - nothing.

Now please compare with the following screenshot:

Do you see the difference? Notice how the user explicitly selected the Emp2, Emp5 and Emp6 values (using the Shift key to select multiple values)? That's what you're gonna get inside your HttpPost action. The AvailableEmpCodeArray collection will contain a single element with the value of 2 and the SelectedEmpCodeArray will contain 2 elements with the values of 5 and 6.

Now to your second problem. If you intend to redisplay the same view from your HttpPost controller action the first thing you need to ensure is that you have assigned values to the AvailalableEmployee and SelectedEmployee collections. This should be done the same way you did in the HttpGet action:

model.AvailalableEmployee.Add(new Employee(1,"Emp1"));
model.AvailalableEmployee.Add(new Scenario(2,"Emp2"));
model.AvailalableEmployee.Add(new Scenario(3,"Emp3"));

model.SelectedEmployee.Add(new Scenario(4,"Emp4"));
model.SelectedEmployee.Add(new Scenario(5,"Emp5"));
model.SelectedEmployee.Add(new Scenario(6,"Emp6"));

or if those values are coming from a database you will have to re-query this database inside the HttpPost action because those values, as I already explained, will never get bound from the view.

Thanks Darine for the quick response. How can I get the values stored in both the listboxes? User will select the values from one listbox to another and then perform other operations before clicking on the submit button.

The user must select the values if you want those values to be sent to your server. That's how HTML works and please learn the basics of HTML. If the user doesn't select anything no matter that you have toggled them between the select boxes, nothing's gonna be sent to the server. I will update my answer with screenshots for you to understand what I mean.

Yes I am new to HTML and learning basics of HTML...Is there any other way I can get values in controller?

I have updated my answer with screenshots. Hopefully you will now understand. You must select the values that you want to be sent to the server. That's how HTML works. Also if you are new to HTML I very strongly suggest you heading towards the w3.org site and start learning it before even getting into ASP.NET MVC. If you don't know the basics of HTML, you really don't need to waste your time with ASP.NET MVC because you will find lots of things strange and you will have hard time understanding them.

Thanks Darin....In my case values are selected when they are moved but then user can perform other operation such as modify department name, unselect some other values. When user clicks on submit then the changes should get saved to the database. In order to do that I need to know original list of values in both the listboxes and the changed list....So looks like I will have to find someother way to do this.

c# - Model does not have values for ListBoxFor in MVC4 - Stack Overflo...

c# jquery asp.net-mvc razor asp.net-mvc-4
Rectangle 27 13

As the names of the methods imply, DropDownListFor() is for creating a <select> (to select 1 option) and ListBoxFor() is for creating a <select multiple> (to select multiple options). While both methods share a lot of common code, they do produce different results.

Adding the multiple="multiple" attribute changes the display, but it does not change the functionality of the code executed by these methods.

DropDownListFor()
private static MvcHtmlString DropDownListHelper()
ListBoxFor()
private static MvcHtmlString ListBoxHelper()
private static MvcHtmlString SelectInternal()
DropDownListHelper()
allowMultiple = false
ListBoxHelper()
allowMultiple = true

Within the SelectInternal() method, the key line of code is

object defaultValue = (allowMultiple) ? htmlHelper.GetModelStateValue(fullName, typeof(string[])) : htmlHelper.GetModelStateValue(fullName, typeof(string));

The value of defaultValue is then used when building html for the <option> elements and is used to set the selected attribute(s).

In the case of ListBoxFor(), the value of defaultValue will be the array defined by your SelectedAssignees property. In the case of DropDownListFor() it return null because the value of your property cannot be cast to string (its an array).

Because defaultValue is null, none of the <option> elements have the selected attribute set and you lose model binding.

As a side note, if you were to set the values of SelectedAssignees in the GET method before you pass the model to the view, you will see that none of them are selected when using DropDownListFor() for the same reasons described above.

Note also that the code for generating the SelectList should just be

vm.TasksFilterGroup.Assignees = new SelectList(employees, "Id", "FullName" });

There is no point setting the 3rd parameter when using either the DropDownListFor() or ListBoxFor() methods because its the value of the property your binding to (SelectedAssignees) that determines which options are selected (the 3rd parameter is ignored by the methods). If you want the opttions matching thode Guid values to be selected, then in the GET method, use

vm.TasksFilterGroup.SelectedAssignees= new string[]{ "51b6f06a-e04d-4f98-88ef-cd0cfa8a2757", "51b6f06a-e04d-4f98-88ef-cd0cfa8a2769" };

This is a great and in depth answer. Very insightful.

asp.net mvc - Why does the DropDownListFor lose the multiple selection...

asp.net-mvc asp.net-mvc-5.2
Rectangle 27 13

As the names of the methods imply, DropDownListFor() is for creating a <select> (to select 1 option) and ListBoxFor() is for creating a <select multiple> (to select multiple options). While both methods share a lot of common code, they do produce different results.

Adding the multiple="multiple" attribute changes the display, but it does not change the functionality of the code executed by these methods.

DropDownListFor()
private static MvcHtmlString DropDownListHelper()
ListBoxFor()
private static MvcHtmlString ListBoxHelper()
private static MvcHtmlString SelectInternal()
DropDownListHelper()
allowMultiple = false
ListBoxHelper()
allowMultiple = true

Within the SelectInternal() method, the key line of code is

object defaultValue = (allowMultiple) ? htmlHelper.GetModelStateValue(fullName, typeof(string[])) : htmlHelper.GetModelStateValue(fullName, typeof(string));

The value of defaultValue is then used when building html for the <option> elements and is used to set the selected attribute(s).

In the case of ListBoxFor(), the value of defaultValue will be the array defined by your SelectedAssignees property. In the case of DropDownListFor() it return null because the value of your property cannot be cast to string (its an array).

Because defaultValue is null, none of the <option> elements have the selected attribute set and you lose model binding.

As a side note, if you were to set the values of SelectedAssignees in the GET method before you pass the model to the view, you will see that none of them are selected when using DropDownListFor() for the same reasons described above.

Note also that the code for generating the SelectList should just be

vm.TasksFilterGroup.Assignees = new SelectList(employees, "Id", "FullName" });

There is no point setting the 3rd parameter when using either the DropDownListFor() or ListBoxFor() methods because its the value of the property your binding to (SelectedAssignees) that determines which options are selected (the 3rd parameter is ignored by the methods). If you want the opttions matching thode Guid values to be selected, then in the GET method, use

vm.TasksFilterGroup.SelectedAssignees= new string[]{ "51b6f06a-e04d-4f98-88ef-cd0cfa8a2757", "51b6f06a-e04d-4f98-88ef-cd0cfa8a2769" };

This is a great and in depth answer. Very insightful.

asp.net mvc - Why does the DropDownListFor lose the multiple selection...

asp.net-mvc asp.net-mvc-5.2
Rectangle 27 8

Grrrrrr, I found it. Apparently, the selected items can only be a list of strings. Once i modified my code to pass this in it selected the values.

tvanfosson - thanks for the help and the quick response. greatly appreciated!

asp.net mvc - .NET MVC MultiSelectList and selected values - Stack Ove...

asp.net-mvc multi-select selected
Rectangle 27 4

The reason that Html.DropDownListFor() has an "option" parameter is that dropdown lists, when they don't have a selected value, are blank and you can't see their contents without expanding them.

Listboxes, typically do display their contents, and thus an option is not necessary. An unselected listbox doesn't need something to say "Select an option" because the options are clearly visible.

I think your problem here is that you're using a third party library to re-style a listbox to look like a dropdownlist, and thus it's not behaving the way you would expect a dropdownlist to behave (because it's not a dropdownlist, it's a listbox that just looks like dropdownlist).

The Listboxfor helper doesn't provide this, because it doesn't typically make sense to provide it. All that the option is doing is creating an entry that is first in the list that has an empty value. Thus, when the form is submitted, the empty value will trigger any required validation you may have on the backing property.

So, to do this yourself, you need to add an empty item with just the text you want, and an empty value.

Used DropDownList instead of ListBoxFor, I have chosen ListBox instead of DropDownList because I heard that it fits better multiselect elements. But since it doesn't have a default selected value as a parameter I came back to DropDownList and passed the collection of selected elements to the MultiSelectList Object.

How to add an Option label on ListBoxFor HTML Helper in ASP.Net MVC - ...

asp.net-mvc asp.net-mvc-4 html-helper
Rectangle 27 4

I have an MVC page that submits JSON of selected values from a group of radio buttons.

var dataArray = $.makeArray($("input[type=radio]").serializeArray());

To make an array of their names and values. Then I convert it to JSON with:

var json = $.toJSON(dataArray)

and then post it with jQuery's ajax() to the MVC controller

$.ajax({
url: "/Rounding.aspx/Round/" + $("#OfferId").val(),
type: 'POST',
dataType: 'html',
data: json, 
contentType: 'application/json; charset=utf-8',
beforeSend: doSubmitBeforeSend,
complete: doSubmitComplete,
success: doSubmitSuccess});

Which sends the data across as native JSON data.

You can then capture the response stream and de-serialize it into the native C#/VB.net object and manipulate it in your controller.

To automate this process in a lovely, low maintenance way, I advise reading this entry that spells out most of native, automatic JSON de-serialization quite well.

Match your JSON object to match your model and the linked process below should automatically deserialize the data into your controller. It's works wonderfully for me.

asp.net mvc - How to send a model in jQuery $.ajax() post request to M...

asp.net-mvc jquery asp.net-ajax
Rectangle 27 4

I have an MVC page that submits JSON of selected values from a group of radio buttons.

var dataArray = $.makeArray($("input[type=radio]").serializeArray());

To make an array of their names and values. Then I convert it to JSON with:

var json = $.toJSON(dataArray)

and then post it with jQuery's ajax() to the MVC controller

$.ajax({
url: "/Rounding.aspx/Round/" + $("#OfferId").val(),
type: 'POST',
dataType: 'html',
data: json, 
contentType: 'application/json; charset=utf-8',
beforeSend: doSubmitBeforeSend,
complete: doSubmitComplete,
success: doSubmitSuccess});

Which sends the data across as native JSON data.

You can then capture the response stream and de-serialize it into the native C#/VB.net object and manipulate it in your controller.

To automate this process in a lovely, low maintenance way, I advise reading this entry that spells out most of native, automatic JSON de-serialization quite well.

Match your JSON object to match your model and the linked process below should automatically deserialize the data into your controller. It's works wonderfully for me.

asp.net mvc - How to send a model in jQuery $.ajax() post request to M...

asp.net-mvc jquery asp.net-ajax
Rectangle 27 8

Ok, let's discuss about your example, when PermissionId was int. You posted model of type CreateEditAccountModel to view. When you created this model, PermissionId equal 0 (default value of int). And DropDownListFor in view get this value. Therefore you had no selected values. When you used string type, default value of PermissionId was null, therefore `DropDownListFor taken default value of SelectList.

int?
Nullable<int>
PermissionId

your explanation is relevant. Way back, when I asked this question I didn't understand that DropDownListFor will first evaluate the value of PermissionId and if it's not null, it will make that value selected. Otherwise it would take into account Model.Permissions

This may and may not have to do with question but it may be useful to someone when you let's say create a List<SelectListItem> from linq to entities and convert Int to string Value make sure to trim if you are using SqlFunctions.StringConvert cause it will not render selected = true for preselected value. Not trimming is causing dropdown to have values like so: value = " 1".

asp.net mvc 3 - DropDownListFor - does not select "Selected" value - S...

asp.net-mvc-3 html.dropdownlistfor
Rectangle 27 8

Ok, let's discuss about your example, when PermissionId was int. You posted model of type CreateEditAccountModel to view. When you created this model, PermissionId equal 0 (default value of int). And DropDownListFor in view get this value. Therefore you had no selected values. When you used string type, default value of PermissionId was null, therefore `DropDownListFor taken default value of SelectList.

int?
Nullable<int>
PermissionId

your explanation is relevant. Way back, when I asked this question I didn't understand that DropDownListFor will first evaluate the value of PermissionId and if it's not null, it will make that value selected. Otherwise it would take into account Model.Permissions

This may and may not have to do with question but it may be useful to someone when you let's say create a List<SelectListItem> from linq to entities and convert Int to string Value make sure to trim if you are using SqlFunctions.StringConvert cause it will not render selected = true for preselected value. Not trimming is causing dropdown to have values like so: value = " 1".

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

asp.net mvc 3 - DropDownListFor - does not select "Selected" value - S...

asp.net-mvc-3 html.dropdownlistfor
Rectangle 27 2

//Manually add a "Select One" with value 0 to the SelectList

This isn't an answer to why "" is not being turned into 0, but a way to avoid that issue in the first place.

List<SpecialProject> specialProjectsForSelectBox = new List<SpecialProject>();
specialProjectsForSelectBox.Add(new SpecialProject(0, "* Select One *"));
specialProjectsForSelectBox.AddRange(specialProjectBusinessLogic.FindAllActive());

asp.net mvc - auto binding not converting empty string to 0 for int mo...

asp.net-mvc binding
Rectangle 27 3

The problem I had getting the MultiSelectList to display with defaults selected was that I was using @Html.DropDownListFor(...) to display the multi select list instead of @Html.ListBoxFor(...). Confusingly, DropDownListFor will display a multi select list if you specify the HTML attributes to force it to do so, but the default values will not work, because it's only intended to have one default - the following will therefore not have any defaults selected:

List<string> myStrings;
myStrings = new List<string>();
myStrings.Add("aaa");
myStrings.Add("bbb");
myStrings.Add("ccc");

ViewData["MyStringsDropdown"] = new MultiSelectList(
    myStrings.Select(abc => new { StringId = abc, Title = abc + "Title" }),
    "StringId",
    "Title",
    myStrings.Where(str => str == "aaa" || str == "ccc").ToList()
);

...

@Html.DropDownListFor(model => model.MyStrings, (MultiSelectList)ViewData["MyStringsDropdown"], new { size = "10", multiple = "multiple" })

However, the following will display the defaults of "aaa" and "ccc" as selected:

@Html.ListBoxFor(model => model.MyStrings, (MultiSelectList)ViewData["MyStringsDropdown"], new { size = "10", multiple = "multiple" })

But here's the real kicker; ASP.NET sometimes seems cache the type of the control, so you can replace the DropDownListFor with the ListBoxFor and it will still not pre-select any defaults until you restart the IIS worker process. I find that really strange, and it threw me for a while.

asp.net mvc - .NET MVC MultiSelectList and selected values - Stack Ove...

asp.net-mvc multi-select selected
Rectangle 27 1

I believe that it pulls the selected items from the model, not from the list of items. Make sure that your StatesOfPractice model property is populated with the items that you want selected. That is, the StatesOfPracticeList model property provides the set of items used to populate the list. The model property StatesOfPractice which will be the set of selected property values when the form is posted, should also contain the default selected values when the view is rendered. Under the hood it uses the HtmlHelper GetModelStateValue method to find the selected value(s) for any select list. I presume this is done so that it is simpler to maintain the selected values when there is a validation error and the form is rerendered with the model state errors.

asp.net mvc - .NET MVC MultiSelectList and selected values - Stack Ove...

asp.net-mvc multi-select selected
Rectangle 27 17

In HTML a dropdown box sends only simple scalar values. In your case that would be the id of the selected book:

@Html.DropDownList("selectedBookId", (SelectList)ViewBag.Books)

and then adapt your controller action so that you will retrieve the book from the id that gets passed to your controller action:

[Authorize]
[HttpPost]
public ActionResult Action(string selectedBookId)
{
    if (ValidateFields()
    {
        Book book = FetchYourBookFromTheId(selectedBookId);
        var data = GetDatasAboutBookSelected(book);
        ViewBag.Data = data;
        return View();
    }
    return View();
}

It works! Thanks a lot :)

I have another question about that. In fact, the DropDownList selected value returns the value of the ToString() method of Book . So I have to put the Ids in my DropDownList, but I would like the list to display the title and the selected value to be the Id. Is there a way to do that? For now, I use this way : the ToString() method returns "Id - Title" and I use SubString() to keep only the Id. But I would like the DropDownList to display only the Title without the Id.

The SelectList class that you are passing to the DropDown is an IEnumerable<SelectListItem> where SelectListItem has 2 properties: Value and Text. You could set the Value to the Id of your Book instance and the Text to whatever format you want.

@Darin Dimitrov, It's tremendous! That is what I would like to do! You are the wizard:).

c# - Get the selected value of a DropDownList. Asp.NET MVC - Stack Ove...

c# .net asp.net-mvc razor asp.net-mvc-4
Rectangle 27 17

In HTML a dropdown box sends only simple scalar values. In your case that would be the id of the selected book:

@Html.DropDownList("selectedBookId", (SelectList)ViewBag.Books)

and then adapt your controller action so that you will retrieve the book from the id that gets passed to your controller action:

[Authorize]
[HttpPost]
public ActionResult Action(string selectedBookId)
{
    if (ValidateFields()
    {
        Book book = FetchYourBookFromTheId(selectedBookId);
        var data = GetDatasAboutBookSelected(book);
        ViewBag.Data = data;
        return View();
    }
    return View();
}

It works! Thanks a lot :)

I have another question about that. In fact, the DropDownList selected value returns the value of the ToString() method of Book . So I have to put the Ids in my DropDownList, but I would like the list to display the title and the selected value to be the Id. Is there a way to do that? For now, I use this way : the ToString() method returns "Id - Title" and I use SubString() to keep only the Id. But I would like the DropDownList to display only the Title without the Id.

The SelectList class that you are passing to the DropDown is an IEnumerable<SelectListItem> where SelectListItem has 2 properties: Value and Text. You could set the Value to the Id of your Book instance and the Text to whatever format you want.

@Darin Dimitrov, It's tremendous! That is what I would like to do! You are the wizard:).

c# - Get the selected value of a DropDownList. Asp.NET MVC - Stack Ove...

c# .net asp.net-mvc razor asp.net-mvc-4
Rectangle 27 139

There really isn't a need to do this unless you insist on the value of 0. The HtmlHelper DropDownList extension allows you to set an option label that shows up as the initial value in the select with a null value. Simply use one of the DropDownList signatures that has the option label.

<%= Html.DropDownList( "DropDownValue",
                       (IEnumerable<SelectListItem>)ViewData["Menu"],
                        "-- Select One --" ) %>

What if you actually do insist on the value of 0? If the value is null/an empty string, it can cause problems with model binding.

If you are expecting it back as an int, then I would use int? and still leave it null if no selection has been made.

The problem with this is solution is that you lose your selected item.

@Html.DropDownListFor( m => m.MenuSelection, (IEnumerable<SelectListItem>)ViewBag.Menu, "Select One", null )
htmlAttributes

@tvanfosson - Thank you for clarifying. I tried to use it with a Complex type as the type for the IEnumerable in the SelectList. I had to specify the dataValueField and the dataTestField which made this not work when adding an optionLabel value. It probably could have worked with a little more effort but I just used one of the alternative solutions. Thanks anyway though!

How can I add an item to a SelectList in ASP.net MVC - Stack Overflow

asp.net-mvc selectlist