Jan Palas
Jan Palas

Reputation: 1895

Is it possible to use ValueTuple as model in View?

Is it possible to use value tuples as 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 setup, exception is raised when page is rendered. I am using .NET 4.6.2 with System.ValueTuple NuGet package installed.

enter image description here

Upvotes: 10

Views: 5619

Answers (4)

Camilo Terevinto
Camilo Terevinto

Reputation: 32068

By doing some testing, I found the following:

Does not work (generates hundres of view compilation errors):

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

Does 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:

By looking at the GitHub issue for this (here), it seems that at Design Time Razor supports C# 7, but not at Compile/Run Time.

Update: (2+ years after the initial answer)

In .NET core 3.1 the following works perfectly for a partial view model

 @model (int Page, string Content, int PageSize, int FileLinkId)

Upvotes: 15

Jan Palas
Jan Palas

Reputation: 1895

Did some experimenting after a while and I got it working with the syntax from question's text. Ie. both these options are working now:

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

That means there is no need to explicitly state ValueTuple keyword anymore.

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

EDIT: Also works in Visual Studio 2019

Upvotes: 4

PBo
PBo

Reputation: 519

Interestingly, somehow the solution offered did not 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 worked:

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

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

Upvotes: 0

Leo Hendry
Leo Hendry

Reputation: 1423

Yes it is. I was able to get this fully working.

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

My environment:

  • Visual Studio 15.3 (currently the latest stable version of 2017)
  • .NET Core 1.1
  • LangVersion = latest
  • Project previously upgraded from .NET Core 1.0 / Visual Studio 2015
  • No expicit setting the Razor C# version.

References:

Upvotes: 3

Related Questions