Modelbinder with dropdown in asp.net mvc

Here's what I'm trying to do:

I have a Task object with a TaskName property and a TaskPriority property .

Now in html I have:

<td><%=Html.TextBox("Task.TaskName") %></td>
<td><%=Html.DropDownList("Task.TaskPriority",new SelectList(ViewData.Model.TaskPriorities,"ID","PriorityName")) %></td>

      

The controller action looks like this:

public ActionResult Create(Task task){
    //task.TaskName has the correct value
    //task.TaskPriority is null - how should the html look so this would work ?
}

      

EDIT In the example below (from Schotime):

public class Task
{
    public int name { get; set; }
    public string value { get; set; } // what if the type of the property were Dropdown ?
       // in the example I gave the Task has a property of type: TaskPriority.
}

      

+1


source to share


1 answer


This should work.

Three classes:

    public class Container
    {
        public string name { get; set; }
        public List<Dropdown> drops { get; set; }
    }

    public class Dropdown
    {
        public int id { get; set; }
        public string value { get; set; }
    }

    public class Task
    {
        public int name { get; set; }
        public TaskPriority priority { get; set; }
    }

    public class TaskPriority
    {
        public string value { get; set; }
        ...
    }

      

Controller:



    public ActionResult Tasks()
    {
        List<dropdown> ds = new List<Dropdown>();
        ds.Add(new Dropdown() { id = 1, value = "first" });
        ds.Add(new Dropdown() { id = 2, value = "second" });

        ViewData.Model = new Container() { name = "name", drops = ds };

        return View();
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Tasks(Task drops)
    {
        //drops return values for both name and value
        return View();
    }

      

Type: strongly typed Viewpage<Container>

<%= Html.BeginForm() %>
<%= Html.TextBox("drops.name") %>
<%= Html.DropDownList("drops.priority.value",new SelectList(ViewData.Model.drops,"id","value")) %>
<%= Html.SubmitButton() %>
<% Html.EndForm(); %>

      

When I debugged it worked as expected. Not sure what you are doing wrong if you have something similar to this. Greetings.

-1


source







All Articles