Search code examples
c#htmlasp.netasp.net-mvc

The model item passed into the ViewDataDictionary is of type 'x', but this ViewDataDictionary instance requires a model item of type 'y'


I have file files at these locations:

Views/Journals/AddOrEdit.cshtml
Views/Trades/AddOrEdit.cshtml

I want to render the Journal view inside the Trades view.


When this code below runs, I get the error message (below):

await Html.PartialAsync("AddOrEdit", Model.Journal);

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'TradeJournal.Models.Journal', but this ViewDataDictionary instance requires a model item of type 'TradeJournal.Models.Trade'.


Here is my TradesController.cs:

// GET: Trades/Details/{Id}
public async Task<IActionResult> Details(int? id)
{
    // nie znaleziono/istnieje id 
    if (id == null) return NotFound();
    

    var trade = await _context.Trades
        .FirstOrDefaultAsync(m => m.Id == id);

    //nie znaleziono trade
    if (trade == null) return NotFound();
     
    //podlaczanie notatki pod trade
    var journal = new Journal
    {
        TradeId = trade.Id
    };

    //tworzenie viewModelu
    var viewModel = new TradesJournalsViewModels
    {
        Trade = trade,
        Journal = journal
    };

    
   //zwracamy oba
    return View(viewModel);
}

Here is Journals/AddOrEdit.cshtml:

@model TradeJournal.Models.Journal

@{
    ViewData["PageTitle"] = "Journals";
    ViewData["PageActionText"] = "+ Add note";
    ViewData["PageActionUrl"] = "/Journals/AddOrEdit";

    var tools = new[] {
        "Bold", "Italic", "Underline", "StrikeThrough",
        "FontName", "FontSize", "FontColor", "BackgroundColor",
        "LowerCase", "UpperCase", "|",
        "Formats", "Alignments", "OrderedList", "UnorderedList",
        "Outdent", "Indent", "|",
        "CreateLink", "Image", "CreateTable", "|", "ClearFormat", "Print",
        "SourceCode", "FullScreen", "|", "Undo", "Redo"
    };
}


<h4>Journal</h4>
<hr />
<div class="row d-flex justify-content-center align-items-center ">
    <div class="col-md-7">
        <form asp-action="AddOrEdit">
            <div asp-validation-summary="ModelOnly"  class="text-danger"></div>
            <input type="hidden" asp-for="Id" />

            <div class="mb-3 w-100">
                <ejs-richtexteditor id="Text" value="@Model.Text">
                    <e-richtexteditor-toolbarsettings items="tools"></e-richtexteditor-toolbarsettings>
                </ejs-richtexteditor>
                <span asp-validation-for="@Model.Text" class="text-danger"></span>
            </div>
  
            <div class="mb-3 ">
                <label asp-for="TradeId" class="control-label"></label>
                <select asp-for="@Model.TradeId" class ="form-control" asp-items="ViewBag.TradeId"></select>
            </div>
            <div class="mb-3">
                <ejs-button cssClass="w-100" id="submit" type="submit" content="Submit"></ejs-button>
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

I've tried to experiment a little with:

using Microsoft.AspNetCore.Mvc;
using TradeJournal.Models;


namespace TradeJournal.ViewModels
{
    public class TradesJournalsViewModels
    {
        public Trade Trade { get; set; }
        public Journal Journal { get; set; }

    }
}

But it didn't help me and the error is still occuring.


Solution

  • It's using the wrong .cshtml view file because AddOrEdit (without further qualification) initially matches ~/Views/Trades/AddOrEdit.cshtml which ASP.NET thinks is "closer" to the current view-context than ~/Views/Journals/AddOrEdit.cshtml...

    So change your view-name argument Action to specify an unambiguous path, like so:

    await Html.PartialAsync( "~/Views/Journals/AddOrEdit.cshtml", this.Model.Journal );