How can I create a dropdown in ASP.NET MVC3?

I am trying to create a dropdown in ASP.NET MVC3 view based on a list of valid values ​​associated with a model.

So far in my model, I had:

namespace NS 
{
    public class Model
    {
        public Model() 
        {
            Status = new List<SelectListItem>();
            Status.Add(new SelectListItem { Text = "New", Value = "New" });
            Status.Add(new SelectListItem { Text = "PaymentPending", Value = "PaymentPending" });
            Status.Add(new SelectListItem { Text = "PaymentProcessed", Value = "PaymentProcessed" });
            Status.Add(new SelectListItem { Text = "Dispatched", Value = "Dispatched" });
            Status.Add(new SelectListItem { Text = "Complete", Value = "Complete" });
            Status.Add(new SelectListItem { Text = "Cancelled", Value = "Cancelled" });
        }

        public List<SelectListItem> Status { get; set; }
    } // class Model
} // NS

      

(obviously trimming unnecessary material)

Then in my opinion I have:

@model NS.Model
@Html.DropDownListFor(Model.Status)

      

As you can see from the answers on SO, it looks like. But I am getting the error:

Compiler error message: CS1501: Overload for 'DropDownListFor' method takes 1 argument

Any hints that are much appreciated.

+3


source to share


2 answers


the error message is pretty self-explanatory , the DropDownListFor helper takes two arguments.

change your model to have the property contain the selected value

public class Model
{
public Model() {
  Status = new List<SelectListItem>();
  Status.Add(new SelectListItem { Text = "New", Value = "New" });
  Status.Add(new SelectListItem { Text = "PaymentPending", Value = "PaymentPending" });
  Status.Add(new SelectListItem { Text = "PaymentProcessed", Value = "PaymentProcessed" });
  Status.Add(new SelectListItem { Text = "Dispatched", Value = "Dispatched" });
  Status.Add(new SelectListItem { Text = "Complete", Value = "Complete" });
  Status.Add(new SelectListItem { Text = "Cancelled", Value = "Cancelled" });
}
public List<SelectListItem> Status { get; set; }
public string SelectedVal{get;set;}
} 

      



then in the view

@NS.Model
@Html.DropDownListFor(x=> x.SelectedVal, x.Status)

      

+5


source


The first parameter is the selected dropdown value from the model. The second value is a list of statuses.



@Html.DropDownListFor(x=> x.SelectedValue, Model.Status)

      

0


source







All Articles