加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 从控制器或视图模型创建下拉列表

发布时间:2020-12-16 09:49:06 所属栏目:asp.Net 来源:网络整理
导读:如何在控制器中创建SelectList并将其传递给我的视图?我需要给“ – 选择 – ”选项赋值0. 我正在回应replies that I got from Jeremey of Fluent Validation. 这就是我现在拥有的.我的观点模型: [Validator(typeof(CreateCategoryViewModelValidator))]pub
如何在控制器中创建SelectList并将其传递给我的视图?我需要给“ – 选择 – ”选项赋值0.

我正在回应replies that I got from Jeremey of Fluent Validation.

这就是我现在拥有的.我的观点模型:

[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.

解决方法

在您的模型中,更改IList< Category>到SelectList然后像这样实例化它…

List<ParentCategory> parentCategories = categoryService.GetParentCategories();

parentCategories.Insert(0,new ParentCategory(){ Id = "0",Name = "--Select--"});

ParentCategories = new SelectList(parentCategories,"Name");

然后在您的视图中,您只需致电

@Html.DropDownListFor(m => m.ParentCategoryId,Model.ParentCategories);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读