0

I'm new to .NET MVC and I'm trying to develop a simple blog application.

So I have a Post and a Comment model and I would like to display a comments creation form at the bottom of my post.

Here is what I'm trying to do :

@model ASPress.Models.Posts

@{
    ViewData["Title"] = "Details";
}


    <!-- Post Content -->
    <article>
      <div class="container">
        <div class="row">
          <div class="col-lg-8 col-md-10 mx-auto">

            <h1>@Html.DisplayFor(model => model.Title)</h1>

            @Html.DisplayFor(model => model.Content)

          </div>
        </div>
      </div>
    </article>


@model ASPress.Models.Comments
@Html.Partial("~/Views/Comments/Create.cshtml")

And I'm getting the following error :

The 'model' directive may only occur once per document.

If I don't include the second @model statement, I get the following error :

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'ASPress.Models.Posts', but this ViewDataDictionary instance requires a model item of type 'ASPress.Models.Comments'.

I found this tutorial which discuss this issue, but it's from 2016 and I was wondering if they wasn't a simpler way to pass 2 different models (in a similar fashion as what I'm trying to do in my view) Basically I don't really understand why I can't simply use different model items in the view, or even why I need the Comments model to have a creation form...

Any suggestion or remark appreciated! I'm using the SDK .NET Core 2.0.2 on Linux with VS Code

Pierre
  • 4,976
  • 12
  • 54
  • 76
  • Possible duplicates of https://stackoverflow.com/questions/4764011/multiple-models-in-a-view & https://stackoverflow.com/questions/40373595/the-model-item-passed-into-the-dictionary-is-of-type-but-this-dictionary-requ. – Tetsuya Yamamoto Jan 04 '18 at 06:11
  • 1
    `@Html.Partial("Create", new Comments())` –  Jan 04 '18 at 07:06
  • @StephenMuecke You see actually your answer is simple and what I was looking for, whereas in the tutorial I mentioned or the question you marked as duplicated, the result isn't as clear. Thanks! – Pierre Jan 04 '18 at 15:21
  • The 2nd part of the 2nd dupe (passing the wrong model from a view to a partial view) explains it in detail :) –  Jan 04 '18 at 22:04

0 Answers0