简体   繁体   中英

The model item passed into the dictionary is of type .. but this dictionary requires a model item of type

This question and community wiki answer has been added to assist in closing out numerous unanswered questions as discussed in this meta post .


I have some code and when it executes, it throws an exception saying:

The model item passed into the dictionary is of type Bar but this dictionary requires a model item of type Foo

What does this mean, and how do I fix it?

该错误意味着您正在导航到其模型声明为 typeof Foo<\/code>的视图(通过使用@model Foo<\/code> ),但您实际上向它传递了一个 typeof Bar<\/code>模型(请注意,使用术语字典<\/em>是因为模型被传递给通过ViewDataDictionary<\/code>的视图)。

该错误可能是由

将错误的模型从控制器方法传递到视图(或部分视图)<\/strong>

常见示例包括使用创建匿名对象(或匿名对象集合)的查询并将其传递给视图

var model = db.Foos.Select(x => new
{
    ID = x.ID,
    Name = x.Name
};
return View(model); // passes an anonymous object to a view declared with @model Foo

This question already has a great answer, but I ran into the same error, in a different scenario: displaying a List in an EditorTemplate .

I have a model like this:

public class Foo
{
    public string FooName { get; set; }
    public List<Bar> Bars { get; set; }
}

public class Bar
{
    public string BarName { get; set; }
}

And this is my main view :

@model Foo

@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })  
@Html.EditorFor(m => m.Bars)

And this is my Bar EditorTemplate ( Bar.cshtml )

@model List<Bar>

<div class="some-style">
    @foreach (var item in Model)
    {
        <label>@item.BarName</label>
    }
</div>

And I got this error:

The model item passed into the dictionary is of type 'Bar', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[Bar]


The reason for this error is that EditorFor already iterates the List for you, so if you pass a collection to it, it would display the editor template once for each item in the collection.

This is how I fixed this problem:

Brought the styles outside of the editor template, and into the main view :

@model Foo

@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })  
<div class="some-style">
    @Html.EditorFor(m => m.Bars)
</div>

And changed the EditorTemplate ( Bar.cshtml ) to this:

@model Bar

<label>@Model.BarName</label>

Observe if the view has the model required:

View

@model IEnumerable<WFAccess.Models.ViewModels.SiteViewModel>

<div class="row">
    <table class="table table-striped table-hover table-width-custom">
        <thead>
            <tr>
....

Controller

[HttpGet]
public ActionResult ListItems()
{
    SiteStore site = new SiteStore();
    site.GetSites();

    IEnumerable<SiteViewModel> sites =
        site.SitesList.Select(s => new SiteViewModel
        {
            Id = s.Id,
            Type = s.Type
        });

    return PartialView("_ListItems", sites);
}

In my case I Use a partial view but runs in normal views

Consider the partial map.cshtml at Partials/Map.cshtml . This can be called from the Page where the partial is to be rendered, simply by using the <partial> tag:

<partial name="Partials/Map" model="new Pages.Partials.MapModel()" />

This is one of the easiest methods I encountered (although I am using razor pages, I am sure same is for MVC too)

First you need to return an IEnumerable version of your model to the list view.

@model IEnumerable<IdentityManager.Models.MerchantDetail>

Second, you need to return a list from the database. I am doing it via SQL Server, so this is code I got working.

    public IActionResult Merchant_Boarding_List()
        List<MerchantDetail> merchList = new List<MerchantDetail>();
        var model = new MerchantDetail();

        try
        {
            using (var con = new SqlConnection(Common.DB_CONNECTION_STRING_BOARDING))
            {
                con.Open();
                using (var command = new SqlCommand("select * from MerchantDetail md where md.UserGUID = '" + UserGUID + "'", con))
                {
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            model.biz_dbaBusinessName = reader["biz_dbaBusinessName"].ToString();
                            merchList.Add(model);
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
        }

        return View(merchList);

Passing the model value that is populated from a controller method to a view

 public async Task<IActionResult> Index()
 {
   //Getting Data from Database
   var model= await _context.GetData();

   //Selecting Populated Data from the Model and passing to view
   return View(model.Value);
 }

one more thing. if your view is a partial/sub page and the model for that partial view is null for some reason (eg no data) you will get this error. Just need to handle the null partial view model

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM