Can ValueTuple be used as a model in a view?

Can value tuples be used as a model type in views in ASP.NET Core MVC? I mean like this:

Controller:

public IActionResult Index()
{
    ...

    (int ImportsCount, int ExportsCount) importsExports = (imports.Count, exports.Count);
    return View(importsExports);
}

      

View:

@model (int ImportsCount, int ExportsCount)

      

However, using this setting, an exception is thrown when the page is rendered. I am using .NET 4.6.2 with System.ValueTuple NuGet package installed.

enter image description here

+4


source to share


5 answers


After doing some testing, I found the following:

Doesn't work (generates hundres errors kind of compilation):

@model (string, string) 
@model (string x, string y)

      

Does it work :



@model ValueTuple<string, string>
@{ var ConvertedModel = ((string x, string y)Model);

<h1>@Model.Item1 | @ConvertedModel.x </h1>
<h1>@Model.Item2 | @ConvertedModel.y </h1>

      

EDIT:

Looking at the GitHub issue for this ( here ) it seems that during development Razor supports C # 7, but not at compile / runtime.

+9


source


Yes it is. I was able to fully work.

In my case, it was necessary and sufficient to add the Microsoft.CodeAnalysis.CSharp v2.2.0 (no later) NuGet package to the main project.

My environment:



  • Visual Studio 15.3 (currently the latest stable release 2017)
  • .NET Core 1.1
  • LangVersion = last
  • Project previously updated from .NET Core 1.0 / Visual Studio 2015
  • Missing installation of C # version of Razor.

Literature:

+3


source


After a while I experimented and I started working with the syntax from the question text. I.e. both of these options work now:

@model (string, string) 
@model (string x, string y)

      

This means that you no longer need an explicit ValueTuple

keyword ValueTuple

.

My current setup is Visual Studio 15.8.0 and ASP.NET Core 2.1.1.

EDIT: Also works in Visual Studio 2019

+1


source


Interestingly, somehow the suggested solution didn't work,

@model ValueTuple<string, string>
@{ var ConvertedModel = ((string x, string y)Model);

<h1>@Model.Item1 | @ConvertedModel.x </h1>
<h1>@Model.Item2 | @ConvertedModel.y </h1>

      

But below works:

@model ValueTuple<string, string>
@{ (string x, string y) ConvertedModel = (Model);

<h1>@Model.Item1 | @ConvertedModel.x </h1>
<h1>@Model.Item2 | @ConvertedModel.y </h1>

      

0


source


Not sure what scenario this would benefit from compared to viewmodel. But you can define the model in the view as

@Model Tuple<int, int>

      

and access them @Model.ItemN

Also, it can be helpful to strip the resulting exception.

-1


source







All Articles