设置类属性为MVC4 DROPDOWNLIST的某些记录 [英] Set Class Attribute for certain records of Dropdownlist in MVC4

查看:205
本文介绍了设置类属性为MVC4 DROPDOWNLIST的某些记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从数据库填充DROPDOWNLIST,我想通过设置其下课的属性,显示为红色的某些元素。所以,我试过很多方法,后来我创建了一个自定义的HTML帮手DROPDOWNLIST。但它并没有任何意义,尽管它似乎是添加类属性,这paramater不能传递到的Razor视图控制器从。你能帮助PLS?

I populate Dropdownlist from database and I want to show certain elements in red by setting their "class" attribute. So, I tried lots of ways and later I have created a custom HTML Helper for Dropdownlist. But it does not make any sense and although it seems to be added class attribute, this paramater cannot pass to Razor View from Controller. Could you help pls?

MyHelper.cs:

public static MvcHtmlString Custom_DropdownList(this HtmlHelper helper, string name,  IEnumerable<SelectListItem> list, object htmlAttributes)
{        
    TagBuilder dropdown = new TagBuilder("select");
    dropdown.Attributes.Add("name", name);
    dropdown.Attributes.Add("id", name);
    StringBuilder options = new StringBuilder();
    foreach (var item in list)
    {            
        options = options.Append("<option value='" + item.Value + "'>" + item.Text + "</option>");
    }
    dropdown.InnerHtml = options.ToString();
    dropdown.MergeAttributes(new RouteValueDictionary(htmlAttributes));
    return MvcHtmlString.Create(dropdown.ToString(TagRenderMode.Normal));
}



控制器:

private void PopulateMeetingsDropDownList(object selectedMeetings = null)
{
    var meetingsQuery = repository.Meetings
    .Join(repository.Cities, m => m.MeetingCityId, c => c.CityID,
    (m, c) => new
    {
        CityID = c.CityID,
        CityName = c.CityName,
        MeetingDate = m.MeetingStartDate
    }
    )
    .OrderBy(x => x.CityID)
    .AsEnumerable()
    .Select(
    i => new
    {
        CityID = i.CityID,
        Name = string.Format(
        "{0} ({1:dd MMMM yyyy})",
        i.CityName, i.MeetingDate),
        Expired = i.MeetingDate < DateTime.UtcNow
    }
    ).ToList();

    var selectItems = new List<SelectListItem>(meetingsQuery.Count);
    foreach (var record in meetingsQuery)
    {
        var item = new SelectListItem
        {
            Text = record.Name,
            Value = record.Name
        };
        if (record.Expired)
        {
            item.Attributes.Add("class", "disabled"); //!!! Problem on this line
        }
            selectItems.Add(item);
    }
    ViewData["MeetingId"] = new SelectList(meetingsQuery, "CityID", "Name", selectedMeetings);
}  

但以这种方法我得到一个错误后,'System.Web.Mvc.SelectListItem'不包含定义'属性',没有扩展方法'属性'接受一个类型的第一个参数...。所以,我想我需要使用其他财产或辅助分配类的属性自定义racords(没有问题的过滤记录的如果(record.Expired)的线)。


查看:

@Html.Custom_DropdownList("MeetingId", ViewData["MeetingId"] as SelectList, new { id = "meetingId"})   

你能澄清我怎么提供呢?先谢谢了。

Could you clarify me how to provide this? Thanks in advance.



这里是改性壳聚糖code具有两个级和残疾人的能力属性:

更新code(对于MyDropdownListFor):

自定义HTML帮助器类:

public static class MyHelpers
{
    public class MySelectItem : SelectListItem
    {
        public string Class { get; set; } 
        public string Disabled { get; set; }
    }

    public static MvcHtmlString MyDropdownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<MySelectItem> list, string optionLabel, object htmlAttributes)
    {
        return MyDropdownList(htmlHelper, ExpressionHelper.GetExpressionText(expression), list, optionLabel, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
    }

    public static MvcHtmlString MyDropdownList(this HtmlHelper htmlHelper, string name, IEnumerable<MySelectItem> list, string optionLabel, IDictionary<string, object> htmlAttributes)
    {
        TagBuilder dropdown = new TagBuilder("select");
        dropdown.Attributes.Add("name", name);
        dropdown.Attributes.Add("id", name);
        StringBuilder options = new StringBuilder();

        // Make optionLabel the first item that gets rendered.
        if (optionLabel != null)
            options = options.Append("<option value='" + String.Empty + "'>" + optionLabel + "</option>");

        foreach (var item in list)
        {
            if(item.Disabled == "disabled")
                options = options.Append("<option value='" + item.Value + "' class='" + item.Class + "' disabled='" + item.Disabled + "'>" + item.Text + "</option>");
            else
                options = options.Append("<option value='" + item.Value + "' class='" + item.Class + "'>" + item.Text + "</option>");
        }
        dropdown.InnerHtml = options.ToString();
        dropdown.MergeAttributes(new RouteValueDictionary(htmlAttributes));
        return MvcHtmlString.Create(dropdown.ToString(TagRenderMode.Normal));
    }
}



控制器:

    private void PopulateMeetingsDropDownList(object selectedMeetings = null)
    {
        var meetingsQuery = repository.Meetings
            .Join(repository.Cities, m => m.MeetingCityId, c => c.CityID,
                (m, c) => new
                {
                    CityID = c.CityID,
                    CityName = c.CityName,
                    MeetingDate = m.MeetingStartDate
                }
            )
            .OrderBy(x => x.CityID)
            .AsEnumerable()
            .Select(
                i => new
                {
                    Value = i.CityID.ToString(),
                    DisplayValue = string.Format(
                        "{0} ({1:dd MMMM yyyy})",
                        i.CityName, i.MeetingDate),
                    Expired = i.MeetingDate < DateTime.UtcNow
                }
            ).ToList();


        var selectItems = new List<MyHelpers.MySelectItem>(meetingsQuery.Count);
        foreach (var record in meetingsQuery)
        {
            var item = new MyHelpers.MySelectItem
            {
                Text = record.DisplayValue,
                Value = record.Value
            };
            if (record.Expired)
            {
                item.Class = "disabled";
                item.Disabled = "disabled";
            }
            selectItems.Add(item);
        }
        ViewBag.MeetingData = selectItems;
    }



查看:

<label>Meeting</label>           
@Html.MyDropdownListFor(m => m.MeetingId, ViewBag.MeetingData as    List<MyHelpers.MySelectItem>, "---- Select ----", 
new { name = "meetingId", id = "meetingId"})  


推荐答案

TL; DR; 您正在使用的SelectList ,但你不吨需要。

TL;DR; You are using SelectList, but you don't need to.

创建一个新的视图模型类,你会传递给视图。它将包含所有你需要的属性,可能是​​这样的:

Create a new view model class, which you will pass to the view. It will contain all the properties you need, and may look like this:

自定义类以保存有关项目信息:

public class CustomSelectItem
{
    public string Text {get;set;}
    public string Value {get;set;}
    public string Class {get;set;}
    public bool Selected {get;set;}
}

由于您使用过这个ViewData的数据,你没有限制,你可以把任何东西在那里。我建议你​​使用,而不是ViewData的ViewBag。

Since you are passing this data using ViewData, you don't have a limitation and you can put anything there. I advise that you use ViewBag instead of ViewData.

在你的控制器,你可以创建一个新的列表与LT; CustomSelectItem&GT; ,并将其传递。当建立集合,如果项目已过期只需设置类属性为禁用或任何你正在使用。这里是code(我跳过了一部分,你在哪里得到的会议):

In your controller you can create a new List<CustomSelectItem> and pass it. When building the collection, if the item is expired just set the Class property to "disabled" or whatever you are using. Here is the code (I skipped the part where you get the meetings):

控制器:

var selectItems = new List<CustomSelectItem>(meetingsQuery.Count);
foreach (var record in meetingsQuery)
{
    var item = new CustomSelectItem
    {
        Text = record.Name,
        Value = record.Name
    };
    if (record.Expired)
    {
        item.Class = "disabled";
    }
    selectItems.Add(item);
}
ViewBag.MeetingData = selectItems;

然后修改您已经创建接受 CustomSelectItem 的集合,而不是 SelectListItem 的定制的辅助方法。您可以直接写HTML,因为你可以访问类属性。

Then modify the custom helper method you have created to accept a collection of CustomSelectItem instead of SelectListItem. You can write directly the HTML, because you have access to the Class property.

自定义helper方法:

public static MvcHtmlString Custom_DropdownList(this HtmlHelper helper, string name, IList<CustomSelectItem> list, object htmlAttributes)
{
    TagBuilder dropdown = new TagBuilder("select");
    dropdown.Attributes.Add("name", name);
    dropdown.Attributes.Add("id", name);
    StringBuilder options = new StringBuilder();
    foreach (var item in list)
    {
        options = options.Append("<option value='" + item.Value + "' class='" + item.Class + "'>" + item.Text + "</option>");
    }
    dropdown.InnerHtml = options.ToString();
    dropdown.MergeAttributes(new RouteValueDictionary(htmlAttributes));
    return MvcHtmlString.Create(dropdown.ToString(TagRenderMode.Normal));
}

一旦做到这一点,你可以调用视图中的助手如下:

Once this is done, you can invoke the helper from the view as follows:

查看:

@Html.Custom_DropdownList("MeetingId", ViewBag.MeetingData as List<CustomListItem>, new { id = "meetingId"})

这篇关于设置类属性为MVC4 DROPDOWNLIST的某些记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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