Question

I am trying to work with an HTML.DropDownList in MVC and am not getting the expected return values. Here is my implementation for the selectList to bind to the drop down -

IEnumerable<status> stat = _provider.GetAllStatuses();
Statuses = new SelectList(stat.ToList(), "id", "name", i.status.id);

And here is my view -

<%= Html.DropDownList("Status",Model.Statuses) %>

I am getting an error when trying to run updatemodel in my controller. I then tried to individually set each object. It turns out that I am not getting a single int from the formvalue as I would expect to. Instead, I am getting a value like "5,10,2,3". I think this is coming from how I set up my selectlist, but I'm not exactly sure. Can anyone see an error in the way I am setting up this dd?

Thanks for any help, and let me know if I can clarify anything.

Was it helpful?

Solution

What does the signature of the post method look like? It (or the model) should have a Status property that's defined as an int. I suspect that you've got more code than you're showing us that is listing all the potential statuses on the page (hidden fields?) and that's what you are seeing posted back as an array of ints.

It should look something like:

 public ActionResult PostAction( int status, .... )
 {
   ... status will contain the selected value from the dropdown ...
 }

OTHER TIPS

This is how I am doing it:

var stat = _provider.GetAllStatuses(); 
myViewDataObject.Statuses = new SelectList(stat, "id", "name", i.status.id); 

stat is an IEnumerable. Statuses is of type SelectList. You don't need ToList() if you are returning an IEnumerable or IQueryable from your provider.

My view inherits from

System.Web.Mvc.Viewpage<MyProject.Models.MyViewDataClass>

which looks like this:

class MyViewDataClass
{
    public int StatusID { get; set; }
    public SelectList Statuses { get; set; }
}

In the controller, I am accepting a FormsCollection object, and using the model binder to update it:

public ActionResult Edit(FormCollection collection)
{
   var myViewDataObject = new MyViewDataClass();
   UpdateModel(myViewDataObject);
}

More info at http://nerddinnerbook.s3.amazonaws.com/Part6.htm

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top