I have used web grid to display employee name, and the projects in a drop down against each employee. For Projects drop down column I have to display the date as column heading which is returned from a HTML helper. i.e. as per the below code instead of column heading "SelectedDate", I have to display the value returned by Html helper (DateTime)@Html.GetNextDate((DateTime)item.SelectedDate, 0)).
Below is the snap shot of 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>
)
)
)
Any help is much appreciated. Thanks Suma
You could add a property to your view model to which your view is strongly typed and which will contain the selected date of the first record for example (since you said in the comments section that all employees have the same value for SelectedDate):
public class MyViewModel
{
public IEnumerable<SelectListItem> ProjectList { get; set; }
public IEnumerable<EmployeeViewModel> employeeProjectsMapper { get; set; }
public DateTime SelectedDate { get; set; }
}
and then inside your controller action simply populate the value for this property:
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);
}
and finally in your view you could use this property to set the header text using the custom HTML helper:
@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>
)
)
)