DropDownListFor人口问题

时间:2010-10-18 23:36:30

标签: asp.net asp.net-mvc asp.net-mvc-2 html.dropdownlistfor

我有以下两个班级:

public class SomeClass
{
  public int SomeClassID { get; set; }
  ...
}

public class AnotherClass
{
  public int AnotherClassID { get; set; }
  public int AnotherClassText { get; set; }
}

我有一个包含以下内容的ViewModel:

public class MyViewModel
{
  public SomeClass { get; set; }
  public List<AnotherClass> { get; set; }
}

我有一个类型为MyViewModel的强类型视图。我想使用DropDownListFor()来获得AnotherClass的列表(value = AnotherClassID,text = AnotherClassText),并将用户选择的任何内容分配给SomeClass.SomeClassID

我该如何做到这一点?

2 个答案:

答案 0 :(得分:2)

型号:

public class SomeClass
{
    public int SomeClassID { get; set; }
}

public class AnotherClass
{
    public int AnotherClassID { get; set; }
    public int AnotherClassText { get; set; }
}

public class MyViewModel
{
    public SomeClass SomeClass { get; set; }
    public List<AnotherClass> AnotherClasses { get; set; }
}

控制器:

[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            AnotherClasses = new[] 
            {
                new AnotherClass { AnotherClassID = 1, AnotherClassText = 1 },
                new AnotherClass { AnotherClassID = 2, AnotherClassText = 2 },
                new AnotherClass { AnotherClassID = 3, AnotherClassText = 3 },
            }.ToList()
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        // TODO: 
        return View(model);
    }
}

查看:

<%= Html.DropDownListFor(x => x.SomeClass.SomeClassID, 
    new SelectList(Model.AnotherClasses, "AnotherClassID", "AnotherClassText"))%>

答案 1 :(得分:0)

您可以向ViewModel添加一个获取并设置SomeClassID的属性,然后按以下方式生成下拉列表:

Html.DropDownListFor(m => m.SomeClassId, 
    m.OtherClasses.Select(o => new SelectListItem { Text = o.Text, value = o.ID})
);