GVKun编程网logo

c# – 如何使用[Display(Name =“”)]作为LoadFromCollection的列标题(c#datagridview列标题)

14

本文的目的是介绍c#–如何使用[Display(Name=“”)]作为LoadFromCollection的列标题的详细情况,特别关注c#datagridview列标题的相关信息。我们将通过专业的研究

本文的目的是介绍c# – 如何使用[Display(Name =“”)]作为LoadFromCollection的列标题的详细情况,特别关注c#datagridview列标题的相关信息。我们将通过专业的研究、有关数据的分析等多种方式,为您呈现一个全面的了解c# – 如何使用[Display(Name =“”)]作为LoadFromCollection的列标题的机会,同时也不会遗漏关于7.0 使用 UISearchDisplayController 的搜索的返回结果 让 TableView 的 Frame 变化、asp.net – 如何在WebGrid中的列标题使用DisplayName数据注释?、asp.net-mvc – 如何从运行时的强类型列表框架视图的Display(Name =)DataAnnotation获取列标题?、ASP.Net/C#将NameValueCollection转换为IDictionary?的知识。

本文目录一览:

c# – 如何使用[Display(Name =“”)]作为LoadFromCollection的列标题(c#datagridview列标题)

c# – 如何使用[Display(Name =“”)]作为LoadFromCollection的列标题(c#datagridview列标题)

在我的MVC 5站点中,我有一个稳定的导出到Excel功能,但用户要求我使列标题“用户友好”.

在我的模型中,我使用[display(Name =“Friendly Column Name”)]注释,它们在View页面上按预期显示,但是当用户触发导出功能时它们不会转移到导出的Excel文件.相反,出现真实姓名.

我知道我可以通过除LoadFromCollection之外的其他方法加载工作表单元格,但我想知道是否仍然可以使用LoadFromCollection并使用模型的display(Name())注释.

这就是我目前拥有的:

public ActionResult ExportToExcel(string _selectedCampus)
    {
        // This is the query result set the user wishes to export to file.
        IEnumerable<Mia1aSec1FayExport> exportQuery = unitOfWork
            .Mia1aSec1FayRepository.Get().Select(n => new Mia1aSec1FayExport
        {
            Campus = n.Campus,StudentName = n.StudentName,CreditsBeforeSchoolYear = n.CreditsBeforeSchoolYear,CreditsDuringSemester1 = n.CreditsDuringSemester1,EligibleFayCount = n.EligibleFayCount,EligibleFayMeetingGoal = n.EligibleFayMeetingGoal
        }).Where(n => n.Campus == _selectedCampus).OrderBy(n => n.StudentName)
        .AsEnumerable();

        // The current iteration saves the table contents,but without the   
        // [display{Name"xxx)] annotation from the model.

        byte[] response;   
        using (var excelFile = new ExcelPackage())
        {
            excelFile.Workbook.Properties.Title = "MIA 1A (i) Eligible FAY Students";                
            var worksheet = excelFile.Workbook.Worksheets.Add("Sheet1");                   
            worksheet.Cells["A1"]
                .LoadFromCollection(Collection: exportQuery,PrintHeaders: true);
            response = excelFile.GetAsByteArray();
        }

        // Save dialog appears through browser for user to save file as desired.
        return File(response,"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","Mia1aSec1Fay.xlsx");
    }

一种解决方法是覆盖标题单元格,但这是不可取的,原因有两个:(1)我已经在模型中将列名称写为注释,这意味着我现在在两个不同的地方写了相同的信息,并且(2) )我必须手动保持信息同步,以防用户需要更多更改,我可能会忘记这样做.

// This loads teh table as seen by the user in the index view.
            worksheet.Cells["A1"].LoadFromCollection(Collection: exportQuery,PrintHeaders: true);

            // Workaround overwrite header cells,as I'm not able to use display Name annotation.
            worksheet.Cells[1,1].Value = "Campus";
            worksheet.Cells[1,2].Value = "Student Name";
            worksheet.Cells[1,3].Value = "Credits Before SY";
            worksheet.Cells[1,4].Value = "Credits During Semester 1";
            worksheet.Cells[1,5].Value = "Legible Population";
            worksheet.Cells[1,6].Value = "Eligible Students Earning 2+ Credits";

在写这篇文章时,我真的希望这不是唯一的选择.必须有一种方法可以在标题中写入显示名称值而不是真实名称.

解决方法

LoadFromCollection仅响应displayName或Description属性,而不响应display属性.

因此,您可以尝试将其中一个属性添加到当前属性中.

[displayName("Friendly Column Name")]
[display(Name = "Friendly Column Name")]
public string StudentName { get; set; }

还要确保在调用LoadFromCollection时将PrintHeaders参数设置为true,但是您说真实的名称会出现,因此可能已经很好了.

7.0 使用 UISearchDisplayController 的搜索的返回结果 让 TableView 的 Frame 变化

7.0 使用 UISearchDisplayController 的搜索的返回结果 让 TableView 的 Frame 变化

 
搜索结果 


出现这种状态是因为键盘的 frame 导致的 UITableView 的 frame 发生变化

解决办法

- (void)searchDisplayController:(UISearchDisplayController *)controller didHideSearchResultsTableView:(UITableView *)tableView {

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];

}



- (void)searchDisplayController:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView {

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide) name:UIKeyboardWillHideNotification object:nil];

}



- (void) keyboardWillHide {

    UITableView *tableView = [[self searchDisplayController] searchResultsTableView];

    [tableView setContentInset:UIEdgeInsetsZero];

    [tableView setScrollIndicatorInsets:UIEdgeInsetsZero];

}

asp.net – 如何在WebGrid中的列标题使用DisplayName数据注释?

asp.net – 如何在WebGrid中的列标题使用DisplayName数据注释?

我有一个Car类,我试图使用WebGrid帮助器在MVC 3视图中显示.下面是Car和它的元数据类.

汽车类:

[MetadataType(typeof(CarMetadata))]
public partial class Car
{
    // car implementation
}

汽车元数据类:

public class CarMetadata
{        
    [displayName("Car Name")]
    [StringLength(100,ErrorMessageResourceType = typeof(ValidationText),ErrorMessageResourceName="CarNameDescriptionLength")]
    [required]
    public string CarName { get; set; }    
}

查看内容:

@model List<Car>
...
var grid = new WebGrid(Model,canPage: true,rowsPerPage: 10);
grid.Pager(WebGridPagerModes.NextPrevIoUs);

@grid.GetHtml(
    htmlAttributes: new { id = "grid" },columns: grid.Columns(
        grid.Column("CarName",?????)
    ));

目标:我想知道如何使用displayName数据注释作为WebGrid(?????)中的列标题文本.有谁知道这是如何实现的?

提前致谢!

解决方法

丑陋的地狱,但它可以工作:
grid.Column(
    "CarName",ModelMetadata.FromLambdaExpression(
        car => car.CarName,new ViewDataDictionary<Car>(new Car())
    ).displayName
)

问题是,WebGrid帮助器完全基于动态数据,绝对没有强大的打字,这是我讨厌它的原因之一. Microsoft的WebMatrix团队必须是C#4.0动态功能的真正粉丝,因为他们的整个API只需要弱类型的对象:-)

MvcContrib Grid好多了

asp.net-mvc – 如何从运行时的强类型列表框架视图的Display(Name =)DataAnnotation获取列标题?

asp.net-mvc – 如何从运行时的强类型列表框架视图的Display(Name =)DataAnnotation获取列标题?

如何在列表脚手架视图的输出中显示[display(Name =“Some Title”)] DataAnnotations“Some Title”

我为这个类创建了一个强类型的列表脚本视图:

public class CompanyHoliday
{
    [Key]
    public int Id { get; set; }

    [required]
    [display(Name = "Datum")]
    [DataType(System.ComponentModel.DataAnnotations.DataType.Date)]
    public DateTime Date { get; set; }

    [required]
    [StringLength(50)]
    [display(Name = "Feiertag Name")]
    public string Name { get; set; }
}

视图看起来像这样:

@model IEnumerable<Zeiterfassung.Domain.CompanyHoliday>

@{
    ViewBag.Title = "Year";
}

<h2>Year</h2>

<p>
    @Html.ActionLink("Create New","Create")
</p>
<table>
<tr>
    <th></th>
    <th>
        Date
    </th>
    <th>
        Name
    </th>
</tr>

@foreach (var item in Model) {
<tr>
    <td>
        @Html.ActionLink("Edit","Edit",new { id=item.Id }) |
        @Html.ActionLink("Details","Details",new { id=item.Id }) |
        @Html.ActionLink("Delete","Delete",new { id=item.Id })
    </td>
    <td>
        @String.Format("{0:g}",item.Date)
    </td>
    <td>
        @item.Name
    </td>
</tr>
}

</table>

但是,我不想在表头中使用“日期”和“名称”。我想要动态地呈现“基准”和“飞标名”。

实际列标题应来自display DataAnnotation。

我该如何做?

解决方法

一个旧主题的位,但我想出了一个扩展方法来处理这个。

让我说我的模型是:

public class MyModel
{
    [display(Name = "Some Property")]
    public string SomeProp { get; set; }
}

将此方法放入静态类中:

namespace Web.Extensions
{
    public static class HtmlHelperExtensions
    {
        public static MvcHtmlString displayNameFor<TModel,TProperty>(this HtmlHelper<IEnumerable<TModel>> helper,Expression<Func<TModel,TProperty>> expression)
        {
            var name = ExpressionHelper.GetExpressionText(expression);
            name = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
            var Metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => Activator.CreateInstance<TModel>(),typeof(TModel),name);
            return new MvcHtmlString(Metadata.displayName);
        }
    } 
}

然后在您的View中,它正在使用IEnumerable< MyModel>,您可以使用它:

@using Web.Extensions
@model IEnumerable<MyModel>

<table>
    <tr>
        <th>
            @Html.displayNameFor(m => m.AvgElecCost)
        </th>

生成的HTML将是:

<th>
            Some Property
        </th>

希望有帮助!

ASP.Net/C#将NameValueCollection转换为IDictionary?

ASP.Net/C#将NameValueCollection转换为IDictionary?

我正在努力帮助我的儿子升级我去年为他建造的网站.他想实施Amazon Simple Pay.我很接近它,但有一个错误,我不知道如何解决.这是一个用C#完成的ASP.Net站点.我是一名未受过培训的(自学成才的)开发人员,请用简单的语言说.

总结

以上是小编为你收集整理的ASP.Net/C#将NameValueCollection转换为IDictionary?全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

今天的关于c# – 如何使用[Display(Name =“”)]作为LoadFromCollection的列标题c#datagridview列标题的分享已经结束,谢谢您的关注,如果想了解更多关于7.0 使用 UISearchDisplayController 的搜索的返回结果 让 TableView 的 Frame 变化、asp.net – 如何在WebGrid中的列标题使用DisplayName数据注释?、asp.net-mvc – 如何从运行时的强类型列表框架视图的Display(Name =)DataAnnotation获取列标题?、ASP.Net/C#将NameValueCollection转换为IDictionary?的相关知识,请在本站进行查询。

本文标签: