我怎样才能在.NET MVC多个视图重用一个DropDownList [英] How can I reuse a DropDownList in several views with .NET MVC

查看:103
本文介绍了我怎样才能在.NET MVC多个视图重用一个DropDownList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从我的项目有几个观点具有相同的DropDownList ...

Several views from my project have the same dropdownlist...

所以,在视图模型从该视图我有:

So, in the ViewModel from that view I have :

public IEnumerable<SelectListItem> FooDdl { get; set; }

和控制器我有:

var MyVM = new MyVM() {
    FooDdl = fooRepository.GetAll().ToSelectList(x => x.Id, x => x.Name)
}

到目前为止好......但是I'm在做每个视图/控制器在同一code,它有一个DDL ...

So far so good... But I´m doing the same code in every view/controller that have that ddl...

时,最好的办法做到这一点?

Is that the best way to do that?

感谢

推荐答案

我们还使用了静态类:

public static class SelectLists
{
        public static IList<SelectListItem> CompanyClasses(int? selected)
        {
            var session = DependencyResolver.Current.GetService<ISession>();

            var list = new List<SelectListItem>
                           {
                               new SelectListItem
                                   {
                                       Selected = !selected.HasValue,
                                       Text = String.Empty
                                   }
                           };

            list.AddRange(session.All<CompanyClass>()
                              .ToList()
                              .OrderBy(x => x.GetNameForCurrentCulture())
                              .Select(x => new SelectListItem
                                               {
                                                   Selected = x.Id == (selected.HasValue ? selected.Value : -1),
                                                   Text = x.GetNameForCurrentCulture(),
                                                   Value = x.Id.ToString()
                                               })
                              .ToList());

            return list;
        }
}

在视图中,我们有没有什么特别的:

In the view we have nothing special :

@Html.DropDownListFor(x => x, SelectLists.CompanyClasses(Model))

和有时我们也创建一个EditorTemplate所以它的速度更快重用像这样

And sometime we also create an EditorTemplate so it's faster to reuse like this

型号:

[Required, UIHint("CompanyClassPicker")]
public int? ClassId { get; set; }

EditorTemplate:

EditorTemplate :

@model int?

@if (ViewBag.ReadOnly != null && ViewBag.ReadOnly)
{
    var item = SelectLists.CompanyClasses(Model).FirstOrDefault(x => x.Selected);

    if (item != null)
    {
        <span>@item.Text</span>
    }
}
else
{
    @Html.DropDownListFor(x => x, SelectLists.CompanyClasses(Model))    
}

这篇关于我怎样才能在.NET MVC多个视图重用一个DropDownList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆