ASP.NET MVC Dropdownlistfor with Model of Type List<String>

ASP.NET MVC DropDownListFor with model of type Liststring

To make a dropdown list you need two properties:

  1. a property to which you will bind to (usually a scalar property of type integer or string)
  2. a list of items containing two properties (one for the values and one for the text)

In your case you only have a list of string which cannot be exploited to create a usable drop down list.

While for number 2. you could have the value and the text be the same you need a property to bind to. You could use a weakly typed version of the helper:

@model List<string>
@Html.DropDownList(
"Foo",
new SelectList(
Model.Select(x => new { Value = x, Text = x }),
"Value",
"Text"
)
)

where Foo will be the name of the ddl and used by the default model binder. So the generated markup might look something like this:

<select name="Foo" id="Foo">
<option value="item 1">item 1</option>
<option value="item 2">item 2</option>
<option value="item 3">item 3</option>
...
</select>

This being said a far better view model for a drop down list is the following:

public class MyListModel
{
public string SelectedItemId { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}

and then:

@model MyListModel
@Html.DropDownListFor(
x => x.SelectedItemId,
new SelectList(Model.Items, "Value", "Text")
)

and if you wanted to preselect some option in this list all you need to do is to set the SelectedItemId property of this view model to the corresponding Value of some element in the Items collection.

asp.net MVC - using list of strings in a DropDownListFor

You can generate a collection of SelectListItems from the list of strings and use that with DropDownListFor helper method.

var names = new List<string> {"Adam", "Sam"};
ViewBag.Names = names.Select(f => new SelectListItem() {Value = f, Text = f});

and in the view

@Html.DropDownListFor(f=>f.Name, ViewBag.Names as IEnumerable<SelectListItem>, 
"select one")

mvc Dropdown list with model of type list

Answered by Stephen in comments:

In the view, changed the foreach to a for loop as per the article in Stephen's comment and used DropdDownListFor


@Html.DropDownListFor(m => m[i].VatRateID, (IEnumerable<SelectListItem>)ViewBag.VatRateList)

Also amended the controller to rename the ViewBag property to VatRateList

'
private void PopulateVatRateDropDownList(object selectedVatRate = null)
{
var vatRateQuery = from v in db.VatRate
select v;
ViewBag.VatRateID = new SelectList(vatRateQuery, "VatRateID", "VatRateDescription", selectedVatRate);
}
'

Asp.net MVC DropDownListFor list of lists from model

In dropdownlist instead of Applications i m getting Getting GenericList.Object.

what i have to modify to get Applications name in dropdownlist?

public List<string> Applications { get; set; }//["app1","app2"]

You can try to concatenate string item(s) using the specified separator, like below.

@Html.DropDownListFor(m => m.ApplicationName, new SelectList(Model.ApplicationName.Select(a=>new { Id = a.Id, Applications = String.Join(", ", a.Applications.ToArray())}), "Id", "Applications"), "Select Application", new { @class = "textboxStyle", placeholder = "Select your application...", autofocus = "autofocus", autocomplete = "on", onkeypress = "btnFocusActivate(this, event)", id = "un" })

Test Result

Sample Image

Update:

it's possible to edit/append random number with id at runtime and result like each app as separate options.

To achieve above requirement, as I mentioned in comment, you can try to generate expected data based on your model data in controller action, then pass it to view to populate your dropdown, like below.

var Applications_list = "";

foreach (var item in model.ApplicationName)
{
Applications_list += String.Join(",", item.Applications.ToArray()) + ",";
}

ViewBag.AppList = Applications_list.TrimEnd(',').Split(",").Select((a, index) => new { Id = index, AppName = a });

Html code

@Html.DropDownListFor(m => m.ApplicationName, new SelectList(ViewBag.AppList, "Id", "AppName"), "Select Application", new { @class = "textboxStyle", placeholder = "Select your application...", autofocus = "autofocus", autocomplete = "on", onkeypress = "btnFocusActivate(this, event)", id = "un" })

Test Result

Sample Image

MVC - Show list of strings in DropDownList

Try this,

@Html.DropDownList("DropDown", new List<SelectListItem>
{ new SelectListItem { Text = "Banana", Value = "1", Selected=true},
new SelectListItem { Text = "Apple", Value = "2"},
new SelectListItem { Text = "Orange", Value = "3"}
}, "Select Fruit")

OR

Get value in model

@Html.DropDownListFor(x => x.Id, new List<SelectListItem>
{ new SelectListItem { Text = "Banana", Value = "1", Selected=true},
new SelectListItem { Text = "Apple", Value = "2"},
new SelectListItem { Text = "Orange", Value = "3"}
}, "Select Fruit")

DropDownListFor - display a simple list of strings

<%= Html.DropDownListFor(x => x.Items, Model.Items) %>

You are confusing expressions and statements. The Html helper returns a string, thus you need to use = to output the 'html-value' (and no ; after it).

Update:

Items = new SelectList(new[]
{
new SelectListItem {Text = "One", Value = "One"},
new SelectListItem {Text = "Two", Value = "Two"},
}, "Text", "Value");

Update 2:

Actually for your case you might do it in an even simpler fashion:

public class HomeViewModel
{
public HomeViewModel()
{
Items = new SelectList(new[] { "One", "Two" });
CurrentItem = "Two";
}

public SelectList Items { get; set; }
public string CurrentItem { get; set; }
}

And in the View:

<%= Html.DropDownListFor(x => x.CurrentItem, Model.Items) %>

Formatting a Drop Down List in ASP.NET MVC

Create a SelectList to be used by DropdownListFor() so that you bind the selected option to property SelectedQuarter, but display the 'friendly' name.

View model

public class MyViewModel
{
[Display(Name = "Quarter")]
[Required]
public short? SelectedQuarter { get; set; } // must be a property, not a field!
IEnumerable<SelectListItem> QuarterList { get; set; }
}

Controller

public ActionResult Edit()
{
MyViewModel model = new MyViewModel();
ConfigureViewModel(model);
return View(model);
}

public ActionResult Edit(MyViewModel model)
{
if(!ModelState.IsValid)
{
ConfigureViewModel(model);
return View(model);
}
// model.SelectedQuarter contains the selected value
}

private void ConfigureViewModel(model)
{
model.SelectedQuarter = new List<SelectListItem>()
{
new SelectListItem() { Value = "1", Text = "Q1" },
new SelectListItem() { Value = "2", Text = "Q2" },
new SelectListItem() { Value = "3", Text = "Q3" },
new SelectListItem() { Value = "4", Text = "Q4" },
}
}

View

@model MyViewModel
@using(Html.BeginForm())
{
@Html.LabelFor(m => m.SelectedQuarter)
@Html.DropDownListFor(m => m.SelectedQuarter, Model.QuarterList, "-Please select-")
@Html.ValidationMessageFor(m => m.SelectedQuarter)
<input type="submit" />
}

Create DropDownListFor using strings from a Liststring

I would recommend using the model directly in the view, instead of the ViewBag. Update your action to include a model reference:

public ActionResult ManageUserAccounts()
{
var model = new ManageUserAccountsViewModel();
model.UserList = oUsers.getUsersFullNames();
return View(model);
}

Your model should be updated to include a selected User property:

public class ManageUserAccountsViewModel
{
public string User { get; set; }

[Display(Name = "Users")]
public List<string> UserList { get; set; }
}

Your view should be binding to the model:

@model ManageUserAccountsViewModel

@Html.DropDownListFor(m => m.User, new SelectList(Model.UserList), "Select User")

ASP.NET MVC : DropDownList to model field

@Html.DropDownListFor generates html like

<select id="CarType" name="CarType">
<option value="a">Volvo</option>
<option value="b">Saab</option>
<option value="c">Mercedes</option>
<option value="d">Audi</option>
</select>

so as you can see they are simple strings(in your case both value and text are the same). when you select one posting form will produce something like that:

...
CarType="a"
...

You can do several tricks but question is it worth doing it and do you really need it.

Normally your model should have field CarrerName and dropdownlist should be bound to it. In Controller Action which accepts form submission you should rehydrate Carrer from database or other store using CarrerName (this is why we asked about id).

I understand that Skills are some kind of dictionary that does not change much. Options for storing are(there maybe some others that i am not aware):

  1. save your dictionary to Session before presenting form or better after logon if this dictionary does not change. You can access it after form submission and find apropriate key (best int or guid)
  2. System.Web.Caching.Cache.
  3. TempData.
  4. Database.

this options have its cons and pros about which you must read because i don't know your application specification.

If you need this data before submission in view or javascript you have to do it yourself ( there is no simple one-liner). I can help but i dont know what do you want to achieve.



Related Topics



Leave a reply



Submit