MaxK123
MaxK123

Reputation: 450

ASP.NET Core 6 MVC how use @model in both shared layout and view

I have an ASP.NET Core 6 project where I want to have a cart in my navbar by taking a dbcontext into a model dynamic and then looping through it to get some values, however I got in to the problem where I use a model called TblOrderItem inside the view and I want to use the model dynamic in my shared layout, but I get the error

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Dynamic.ExpandoObject', but this ViewDataDictionary instance requires a model item of type 'xxx.DataDB.TblOrderItem'.

I want to have this in my layout view:

@model dynamic

And this in my index:

@model xxx.TblOrderItem

Thanks in advance!

Best regards Max

Upvotes: 0

Views: 1090

Answers (1)

Tupac
Tupac

Reputation: 2910

You can put the value you get into a List, and then use @@model IEnumerable<xxxxx.Models.xxx> on the View, like this:

Controller:

 public class TestController : Controller
    {
        public IActionResult Index()
        {
            Test test = new Test();
            test.id = 1;
            test.name = "test";
            test.address = "address";

           List<Test> tests = new List<Test>();
            tests.Add(test);

            return View(tests);
        }
    }

Model:

 public class Test
    {
        public int id { get; set; }
        public string name { get; set; }
        public string address { get; set; }
   

    }

View:

@model IEnumerable<WebApplication220.Models.Test>

@foreach (var item in Model)
{
    <div>@item.id</div>
    <div>@item.name</div>
    <div>@item.address</div>

}

Result:

enter image description here

Upvotes: 1

Related Questions