【问题标题】:How do I pass complex types to Html.LabelFor?如何将复杂类型传递给 Html.LabelFor?
【发布时间】:2021-10-19 21:14:49
【问题描述】:

这样不行,错误是:

预期的“,”

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

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

【问题讨论】:

    标签: c# .net asp.net-mvc model-view-controller


    【解决方案1】:

    你有两个选择。

    第一种,使用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)
    

    【讨论】:

    • 谢谢,我不知道这样做是为了什么——非常方便:@{ ViewBag.Title = "Home Page"; OrganizationDetails 详细信息 = ViewBag.OrganizationDetails; // 本地变量,很好! }
    • 我这样做了: var model = new Views.FooViewModel(); model.Organization = 组织; model.OrganizationDetails = 组织详情; model.OrganizationBuilding = 组织建设;返回视图(模型);
    • @123 Иванов: 没错!这就是我们通常所做的就是定义一个类来封装所有数据并将其作为模型传递给强类型视图。
    【解决方案2】:

    试试这个:

    @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" })
    

    我没试过。

    【讨论】:

      猜你喜欢
      • 2016-10-01
      • 1970-01-01
      • 2013-10-18
      • 2020-09-18
      • 2016-06-12
      • 1970-01-01
      • 2010-09-21
      • 2014-07-05
      • 1970-01-01
      相关资源
      最近更新 更多