创建您的控制器或视图模型一个DropDownList [英] Creating a dropdownlist from your controller or view model
问题描述
我怎么会在我的控制器创建的SelectList并把它传递给我的看法?我需要给 - 选择 - 选项的值为0
How would I create a SelectList in my controller and pass it to my view? I need to give the "-- Select --" option a value of 0.
我回应回答说,我是从流利验证的Jeremey了
I'm responding to the replies that I got from Jeremey of Fluent Validation.
这是我目前有。我的视图模型:
This is what I currently have. My view model:
[Validator(typeof(CreateCategoryViewModelValidator))]
public class CreateCategoryViewModel
{
public CreateCategoryViewModel()
{
IsActive = true;
}
public string Name { get; set; }
public string Description { get; set; }
public string MetaKeywords { get; set; }
public string MetaDescription { get; set; }
public bool IsActive { get; set; }
public IList<Category> ParentCategories { get; set; }
public int ParentCategoryId { get; set; }
}
我的控制器。
public ActionResult Create()
{
List<Category> parentCategoriesList = categoryService.GetParentCategories();
CreateCategoryViewModel createCategoryViewModel = new CreateCategoryViewModel
{
ParentCategories = parentCategoriesList
};
return View(createCategoryViewModel);
}
这是我在我的观点:
@Html.DropDownListFor(x => x.ParentCategoryId, new SelectList(Model.ParentCategories, "Id", "Name", Model.ParentCategoryId), "-- Select --")
如何创建在控制器或视图模型一个下拉列表,并把它传递给看法?我需要 - 选择 - 选项,值为0
How do I create a dropdown list in the controller or view model and pass it to the view? I need the "-- Select --" option to have a value of 0.
推荐答案
在你的模型中,将的IList&LT;类别&GT;
到的SelectList
,然后实例像这样...
In your model, change the IList<Category>
to SelectList
and then instantiate it like this...
List<ParentCategory> parentCategories = categoryService.GetParentCategories();
parentCategories.Insert(0, new ParentCategory(){ Id = "0", Name = "--Select--"});
ParentCategories = new SelectList(parentCategories, "Id", "Name");
然后在你的观点,你可以简单地调用
Then in your view you can simply call
@Html.DropDownListFor(m => m.ParentCategoryId, Model.ParentCategories);
这篇关于创建您的控制器或视图模型一个DropDownList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!