简体   繁体   中英

asp.net mvc 5 get name of variable passed into view

I am trying to get the variable name of the model i'm passing into a partial view, but am unable to figure this out. In the _MetricsTotal Partial View, how do I get "nameOfVariable"?

Metrics Model

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

Controller

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

View1

@{
    @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))

If you want that label you'll need to pass that in as well.

@model MyViewModel

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

Make a new class

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

Then you call it in the parent view

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

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

Example

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM