Can a C# named Tuple be used as an MVC page model type?
Asked Answered
S

1

7

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);
Sarajane answered 23/8, 2017 at 14:28 Comment(2)
I would recommend doing this for the same reason that I was given to not have your model implement List<T>: What happens if you need to add another property/collection? Yes, you can expand your Tuple easier than just a list, however, it could get messy very easily. Make a Model. It's MVC, not TVC.Swen
I didn't read about the new C# 7 features yet, but maybe: ValueTuple<string, int>?Fixation
J
6

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)

Jupiter answered 23/8, 2017 at 14:38 Comment(3)
Yeppers; I did end up doing this, but sure wish I could have done something like: @model (string: Name, int: Age); I can live with this for now. :-) Thanks.Sarajane
Yes, this is a bug in Razor 2.0.0 - tracked here github.com/aspnet/Razor/issues/1592. This will be fixed in 2.1.0Jessie
@RyanNowak - Thanks - I'll keep track and update my answer in timeJupiter

© 2022 - 2024 — McMap. All rights reserved.