如何将复杂类型传递给 Html.LabelFor?

How do I pass complex types to Html.LabelFor?

这样不行,错误是:

Expected ","

    @Html.LabelFor(ViewBag.OrganizationDetails => (string)ViewBag.OrganizationDetails.AddressLegal, htmlAttributes: new { @class = "control-label col-md-2" })

OrganizationDetails是一个class,AddressLegal是一个字符串(需要它的值)

试试这个:

@model ParentModel

@Html.LabelFor(model => model.Name)
@Html.LabelFor(model => model.Child.Name)

在你的情况下应该是:

@model ViewBag.OrganizationDetails

@Html.LabelFor(model => model.AddressLegal, new { @class = "control-label col-md-2" })

@model ViewBag

@Html.LabelFor(model => model.OrganizationDetails.AddressLegal, new { @class = "control-label col-md-2" })

没试过

你有两个选择。

第一种,当使用ViewBag时:

@using Models
@{
    ViewBag.Title = "Home Page";
    OrganizationDetails details = ViewBag.OrganizationDetails;
}

@Html.LabelFor(m => details.AddressLegal, htmlAttributes: new { @class = "control-label col-md-2" })

第二种,通过将模型传递给视图来使用 Html.LabelFor() 的强类型版本:

public ActionResult Index()
{
    var model = new OrganizationDetails() { AddressLegal = "Address" /* set another properties ... */};    
    return View(model);
}

并且在视图中:

@model Models.OrganizationDetails

@Html.LabelFor(m => m.AddressLegal, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.DisplayFor(m => m.AddressLegal)