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);
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
paultechguy
  • 2,318
  • 4
  • 25
  • 34
  • I would recommend doing this for the same reason that I was given to not have your model implement `List`: 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. – krillgar Aug 23 '17 at 14:31
  • I didn't read about the new C# 7 features yet, but maybe: `ValueTuple`? – apocalypse Aug 23 '17 at 14:37

1 Answers1

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)

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
  • 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. – paultechguy Aug 24 '17 at 00:28
  • 2
    Yes, this is a bug in Razor 2.0.0 - tracked here https://github.com/aspnet/Razor/issues/1592. This will be fixed in 2.1.0 – Ryan Nowak Sep 06 '17 at 01:23
  • @RyanNowak - Thanks - I'll keep track and update my answer in time – Gilad Green Sep 06 '17 at 18:35