0

i used c# 7.2 (c# latest minor version (latest))

I want to send two model with Tuple and named items in view. in controller i create tuple with name:

   public ActionResult Create(Guid fitnessPlanId)
        {
            #region GetCurrentFitnessPlan

            var currentFitnessPlan= _service.FitnessPlanRepository.Get(fitnessPlanId, null, null);
            if (currentFitnessPlan == null) return HttpNotFound();

            #endregion
            _currentUser = _service.UserRepository.GetUserByUsername(User.Identity.Name);

           (FitnessPlan fitnessPlan , FitnessPlanDay fitnessPlanDay) tupleModel =(currentFitnessPlan, null);  

            return View(tupleModel);
        }

and in view i wrote this:

@model (FitnessPlan fitnessPlan, FitnessPlanDay fitnessPlanDay)

when use tuple in view like this:

<th>@Html.DisplayNameFor(model => model.fitnessPlan.User.Sex)</th>

DisplayNameFor take me an error:

The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly.

I did research on the Internet, but I did not find any results. How can use Tuple By naming items in view ?

---Fixed---

Regarding the answer Georg Patscheider and this article :Can a C# named Tuple be used as an MVC page model type?

The only way to fix this problem was to change var tupleModel = new Tuple<FitnessPlan, FitnessPlanDay>(currentFitnessPlan, null); in action controller and the model to @model Tuple<FitnessPlan, FitnessPlanDay>on the view and use <th>@Html.DisplayNameFor(model => model.Item1.User.Sex)</th>

arman
  • 649
  • 1
  • 10
  • 27

1 Answers1

0

The clean way to handle this would be to introduce a new ViewModel that wraps FitnessPlan and FitnessPlanDay.

public CreateFitnessPlanViewModel {
    public FitnessPlan Plan { get; set; }
    public FitnessPlanDay Day { get; set; }
}

Razor:

@model CreateFitnessPlanViewModel
<th>@Html.DisplayNameFor(model => model.Plan.User.Sex)</th>

That being said, you can access the elements of tuples with Item1, Item2, ... ItemN:

var tuple = new Tuple<FitnessPlan, FitnessPlanDay>(fitnessPlan, fitnessPlanDay);
var plan = tuple.Item1;
var day = tuple.Item2;

So you can use:

@Html.DisplayNameFor(model => model.Item1.User.Sex)
Georg Patscheider
  • 9,357
  • 1
  • 26
  • 36
  • Right to you. Useful information for people like me :https://stackoverflow.com/questions/45842565/can-a-c-sharp-named-tuple-be-used-as-an-mvc-page-model-type – arman Feb 06 '18 at 16:37
  • OP's method is `Create()` suggesting its a view for creating/editing data which means you cannot use a `Tuple` (it has no paeameterless constructor therefore cannot be bound in the POST method). And view models should **not** contain data models –  Feb 06 '18 at 21:34