Laurence
Laurence

Reputation: 7823

How to preselect MVC Dropdownlistfor?

I have multiple dropdownlists on a page which are being built at runtime. I have a view model with a selectlist. I have tried this post which is great but it is a bit different coz i have a collection of view model on the view. I think I am close but i am not sure how to use DropDownListFor properly. How can I preselect each dropdownlist with different values?

VM

public class categoryVm
{        
    public IEnumerable<SelectListItem> category { get; set; }

    public string SelectedValue { get; set; }
} 

View

@model IEnumerable<categoryVm>
@foreach (var item in Model)
{
   //i think i am missing something here???
   @Html.DropDownListFor(**x => item.SelectedValue**, item.category)
}

Controller

name is one of StaticName and it's like an Id and it's in the list.

var categories = new List<categoryVm>();
var selectlistcolumns = columns.Select(x => new SelectListItem
            {                    
                Value = x.StaticName,
                Text = x.DisplayName
            });

foreach (var column_loopVariable in dtCSV.Columns)
            {
                var category= new categoryVm();                    
                category.category= selectlistcolumns;
                category.SelectedValue = "name";
                categories .Add(category);
            }
     return View(categories);

I would prefer mvc solution than using javascript changing dom.

Upvotes: 0

Views: 5421

Answers (3)

Murali Murugesan
Murali Murugesan

Reputation: 22619

@Html.DropDownListFor(m => item.SelectedValue, new SelectList(item.category))

Upvotes: 0

cackharot
cackharot

Reputation: 698

Try this

var selectlistcolumns = columns.Select(x => new SelectListItem
        {                    
            Value = x.StaticName,
            Text = x.DisplayName,
            Selected = x.DisplayName == "name"  // this sets the selected value
        });

foreach (var column_loopVariable in dtCSV.Columns)
        {
            var category= new categoryVm();                    
            category.category= selectlistcolumns;
            //category.SelectedValue = "name"; // not required
            categories .Add(category);
        }

Also if you notice the signature for Html.DropDownListFor(propExpresstion, selectList) so the first argument as you assumed does not set the selected value. Hope this helps!

Upvotes: 3

Ashwini Verma
Ashwini Verma

Reputation: 7525

Since your controller return List. You should use IList in view page instead of IEnumerable.

@model IList<categoryVm>

for (int i = 0; i < Model.Count; i++) 
{
   @Html.DropDownListFor(m => Model[i].SelectedValue, Model[i].category)
}

View Model IEnumerable<> property is coming back null (not binding) from post method?

Upvotes: 1

Related Questions