2009-01-08 7 views
1

Voici ce que je suis en train de faire:ModelBinder avec dropdownlist dans asp.net mvc

J'ai une entité Task avec une propriété TaskName et une propriété TaskPriority .

Maintenant, dans le code html j'ai:

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

L'action du contrôleur est comme ceci:

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 Dans l'exemple ci-dessous (à partir 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. 
} 
+0

Voulez-vous dire que TaskPriority est une classe ?? Si c'est le cas, vous devez spécifier Task.TaskPriority.PropertyName pour le nom de la liste déroulante. – Schotime

+0

Cela fonctionne en effet :). S'il vous plaît modifier votre réponse afin que je puisse l'accepter. – sirrocco

Répondre

-1

Cela devrait fonctionner.

Trois 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(); 
    } 

Vue: fortement typé Viewpage<Container>

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

Quand je débogués cela a fonctionné comme prévu. Je ne sais pas ce que vous faites mal si vous avez quelque chose de similaire à cela. À la vôtre.

Questions connexes