简体   繁体   English

如何在asp.net-mvc 5视图中访问元组项c#7.2

[英]how can access to tuple item in asp.net-mvc 5 view c#7.2

i used c# 7.2 (c# latest minor version (latest)) 我使用了C#7.2 (C#最新次要版本(最新))

I want to send two model with Tuple and named items in view. 我想在视图中发送两个带有元组和命名项的模型。 in controller i create tuple with name: 在控制器中,我用名称创建元组:

   public ActionResult Create(Guid fitnessPlanId)
        {
            #region GetCurrentFitnessPlan

            var currentFitnessPlan= _service.FitnessPlanRepository.Get(fitnessPlanId, null, null);
            if (currentFitnessPlan == null) return HttpNotFound();

            #endregion
            _currentUser = _service.UserRepository.GetUserByUsername(User.Identity.Name);

           (FitnessPlan fitnessPlan , FitnessPlanDay fitnessPlanDay) tupleModel =(currentFitnessPlan, null);  

            return View(tupleModel);
        }

and in view i wrote this: 鉴于我这样写:

@model (FitnessPlan fitnessPlan, FitnessPlanDay fitnessPlanDay)

when use tuple in view like this: 当在这样的视图中使用元组时:

<th>@Html.DisplayNameFor(model => model.fitnessPlan.User.Sex)</th>

DisplayNameFor take me an error: DisplayNameFor给我一个错误:

The type arguments cannot be inferred from the usage. 不能从用法中推断出类型实参。 Try specifying the type arguments explicitly. 尝试显式指定类型参数。

I did research on the Internet, but I did not find any results. 我曾在Internet上进行过研究,但未找到任何结果。 How can use Tuple By naming items in view ? 如何通过在视图中命名项目来使用Tuple?

---Fixed--- - -固定 - -

Regarding the answer Georg Patscheider and this article : Can a C# named Tuple be used as an MVC page model type? 关于答案Georg Patscheider和本文: 可以将名为Tuple的C#用作MVC页面模型类型吗?

The only way to fix this problem was to change var tupleModel = new Tuple<FitnessPlan, FitnessPlanDay>(currentFitnessPlan, null); 解决此问题的唯一方法是更改var tupleModel = new Tuple<FitnessPlan, FitnessPlanDay>(currentFitnessPlan, null); in action controller and the model to @model Tuple<FitnessPlan, FitnessPlanDay> on the view and use <th>@Html.DisplayNameFor(model => model.Item1.User.Sex)</th> 在动作控制器中,将模型添加到@model Tuple<FitnessPlan, FitnessPlanDay>并使用<th>@Html.DisplayNameFor(model => model.Item1.User.Sex)</th>

The clean way to handle this would be to introduce a new ViewModel that wraps FitnessPlan and FitnessPlanDay . 解决此问题的干净方法是引入一个新的ViewModel,其中包含FitnessPlanFitnessPlanDay

public CreateFitnessPlanViewModel {
    public FitnessPlan Plan { get; set; }
    public FitnessPlanDay Day { get; set; }
}

Razor: 剃刀:

@model CreateFitnessPlanViewModel
<th>@Html.DisplayNameFor(model => model.Plan.User.Sex)</th>

That being said, you can access the elements of tuples with Item1 , Item2 , ... ItemN : 话虽如此,您可以使用Item1Item2 ,... ItemN访问元组的元素:

var tuple = new Tuple<FitnessPlan, FitnessPlanDay>(fitnessPlan, fitnessPlanDay);
var plan = tuple.Item1;
var day = tuple.Item2;

So you can use: 因此,您可以使用:

@Html.DisplayNameFor(model => model.Item1.User.Sex)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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