asp.net mvc 5获取传递给视图的变量名称

时间:2016-06-20 18:30:09

标签: c# asp.net asp.net-mvc razor asp.net-mvc-5

我正在尝试获取模型的变量名称,我正在进入局部视图,但我无法弄清楚这一点。在_MetricsTotal Partial View中,如何获得“nameOfVariable”?

指标模型

public class MetricsModel
{
    public IEnumerable<MetricsDetail> metricsDetail { get; set; }
    public IEnumerable<AttyList> attyList { get; set; }
    public IEnumerable<MatterDataModel> matterdata { get; set; }    
}

控制器

    MetricsModel metricsData = new MetricsModel();
    //Logic to populate some metricsData
    return View("View1", metricsData);

视图1

@{
    @model MVC5.Models.MetricsModel

    List<MVC5.Models.MetricsDetail> fooTotal = new List<MVC5.Models.MetricsDetail>();
    List<MVC5.Models.MetricsDetail> barTotal = new List<MVC5.Models.MetricsDetail>();        
}
@foreach (var item in Model.metricsDetail){
    //Logic to add some items to fooTotal and barTotal

    if (Request.Form["queryType"] != "foo")
    {   
        @Html.Partial("_MetricsTotal", fooTotal)
    }
    else{
        @Html.Partial("_MetricsTotal", barTotal) 
    }
}

_MetricsTotal Partial View

@model IEnumerable<MVC5.Models.MetricsDetail>

<p @{if(nameOfVariable=="fooTotal"){ <text>id = "fooTotalVariable"</text>}} Model.Sum(itemData => itemData.totalHours))

2 个答案:

答案 0 :(得分:1)

如果你想要那个标签,你也需要传递它。

@model MyViewModel

<div>@Model.Name</div><div>@Model.Data.Sum(m => m.totalHours)</div>

制作新课程

public class MyViewModel
{
    public string Name { get; set; }
    public IEnumerable<MVC5.Models.MetricsDetail> Data { get; set; }
}

然后在父视图中调用它

@Html.Partial("_MetricsTotal", new MyViewModel { Name = "fooTotal", Data = fooTotal })

答案 1 :(得分:1)

C#6 nameof operator =&gt; https://msdn.microsoft.com/en-us/library/dn986596.aspx

实施例

@Html.Partial("_MetricsTotal",new MyViewModel { Name = nameof(fooTotal), Data = fooTotal }