I have the following 2 classes:
public class SomeClass
{
public int SomeClassID { get; set; }
...
}
public class AnotherClass
{
public int AnotherClassID { get; set; }
public int AnotherClassText { get; set; }
}
I have a ViewModel that contains the following:
public class MyViewModel
{
public SomeClass { get; set; }
public List<AnotherClass> { get; set; }
}
I have a Strongly-Typed View of type MyViewModel
. I want to use DropDownListFor()
in order to have a list of AnotherClass
(value = AnotherClassID, text = AnotherClassText) and 开发者_运维问答have whatever the user selects be assigned to the SomeClass.SomeClassID
How can I accomplish this?
Model:
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; }
}
Controller:
[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);
}
}
View:
<%= Html.DropDownListFor(x => x.SomeClass.SomeClassID,
new SelectList(Model.AnotherClasses, "AnotherClassID", "AnotherClassText"))%>
You can add a property to your ViewModel that gets and sets the SomeClassID
, then make the dropdown like this:
Html.DropDownListFor(m => m.SomeClassId,
m.OtherClasses.Select(o => new SelectListItem { Text = o.Text, value = o.ID})
);
精彩评论