Search code examples
c#asp.net-core-mvcvaluetuple

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


Solution

  • 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)