Can a C# named Tuple be used as an MVC page model

2020-03-16 17:57发布

问题:

In C# 7 you can have named tuples:

var foo = (Name: "Joe", Age: 42);

If I pass this to a MVC model using:

return View(foo);

Then what syntax should be used in the cshtml file to declare the model? Although this doesn't work, something like...

@model (string Name, int Age);

回答1:

As for current time you can't and need to use

@model Tuple<string, int>
//or
@model ValueTuple<string, int>

For the difference between the two options: What's the difference between System.ValueTuple and System.Tuple?

You can follow on GitHub: Razor throws CompilationFailedException when iterating over named Tuple (I know it is closed as a dup but name is more indicative for current case)