如何从Razor视图引用ViewModel中的属性

时间:2013-07-02 20:15:06

标签: asp.net-mvc asp.net-mvc-4 razor

我有一个视图模型类,它有一个名为Title的属性,我想在Razor的Index视图中呈现

CLASS

public class vmAppointment
{
    public Appointment Appointment { get; private set; }
    public IEnumerable<SelectListItem> EmployeeList { get; set; }
    public string Title { get; set; }
}

INDEX VIEW

@model IEnumerable<JJ.ViewModels.vmAppointment>

<h2>@Model.Title</h2>  WRONG!  how can i reference my property here?

如何在视图中呈现属性值?

1 个答案:

答案 0 :(得分:4)

您的观点是强加到vmAppointment的集合,而不是单个vmAppointment。因此,为了引用Title,您将需要遍历此集合的元素。例如:

@foreach (var appointment in Model)
{
    <div>Appointment title: @appointment.Title</div>
}

或者,如果您希望将视图强类型化为单个vmAppointment而不是集合,则控制器操作将返回此类的单个实例:

vmAppointment model = ...
return View(model);

然后将您的观点强烈输入到单个约会,您就可以直接引用Title属性:

@model JJ.ViewModels.vmAppointment
<h2>@Html.DisplyFor(x => x.Title)</h2>