如何在webgrid中设置动态列标题?

时间:2013-01-03 13:03:38

标签: asp.net-mvc-3 webgrid

我使用网格来显示员工姓名,以及针对每位员工的下拉项目。对于Projects下拉列,我必须将日期显示为从HTML帮助程序返回的列标题。即根据下面的代码而不是列标题“SelectedDate”,我必须显示由Html帮助器(DateTime)返回的值@Html.GetNextDate((DateTime)item.SelectedDate,0))。

以下是View

的快照
    @{
       var grid = new WebGrid(Model.employeeProjectsMapper);
     }

    @grid.GetHtml(
    columns: grid.Columns(
     grid.Column("EmployeeName"),
     grid.Column(
     header: "SelectedDate",
        format:
        @<span>
        @{ var index = Guid.NewGuid().ToString(); }
        @Html.Hidden("employeeProjectsMapper.Index", index)
        @Html.Hidden("employeeProjectsMapper[" + index + "].EmployeeID", (Int64)item.EmployeeID)
        @Html.Hidden("employeeProjectsMapper[" + index + "].SelectedDate",  
       (DateTime)@Html.GetNextDate((DateTime)item.SelectedDate, 0))
        @Html.DropDownList("employeeProjectsMapper[" + index + "].SelectedProject",    
       Model.ProjectList)
        </span>
     )
    )
  )

非常感谢任何帮助。 谢谢 须磨

1 个答案:

答案 0 :(得分:0)

您可以向您的视图模型添加一个属性,您的视图是强类型的,并且其中包含第一条记录的选定日期(例如,因为您在评论部分中说明所有员工对SelectedDate具有相同的值) :

public class MyViewModel
{
    public IEnumerable<SelectListItem> ProjectList { get; set; }
    public IEnumerable<EmployeeViewModel> employeeProjectsMapper { get; set; }

    public DateTime SelectedDate { get; set; }
}

然后在您的控制器操作中只需填充此属性的值:

public ActionResult Index()
{
    var model = new MyViewModel();
    model.ProjectList = ...
    model.employeeProjectsMapper = ...

    // set the SelectedDate property from the first employee record
    // that will be used as header in the selected project column
    model.SelectedDate = model.employeeProjectsMapper.First().SelectedDate;

    return View(model);
}

最后在您的视图中,您可以使用此属性使用自定义HTML帮助程序设置标题文本:

@model MyViewModel

@{
    var grid = new WebGrid(Model.employeeProjectsMapper);
}

@grid.GetHtml(
    columns: grid.Columns(
        grid.Column("EmployeeName"),
        grid.Column(
            header: ((DateTime)Html.GetNextDate(Model.SelectedDate, 0)).ToShortDateString(),
            format:
                @<span>
                    @{ var index = Guid.NewGuid().ToString(); }
                    @Html.Hidden("employeeProjectsMapper.Index", index)
                    @Html.Hidden("employeeProjectsMapper[" + index + "].EmployeeID", (Int64)item.EmployeeID)
                    @Html.Hidden("employeeProjectsMapper[" + index + "].SelectedDate", (DateTime)Html.GetNextDate((DateTime)item.SelectedDate, 0))
                    @Html.DropDownList("employeeProjectsMapper[" + index + "].SelectedProject", new SelectList(Model.ProjectList, "Value", "Text", item.SelectedProject))
                </span>
        )
    )
)