我有以下两个班级:
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
我该如何做到这一点?
答案 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})
);