user1861156
user1861156

Reputation: 169

Passing Model to View

So I'm passing the following view model to my view, but the view is throwing an exception everytime it I try to visit the page. Any explanation as to why this is happening would be great, pointers on how to fix it would be better! Thanks.

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

View Model

public class CategoryIndex
{
    public string Title { get; set; }
    [DisplayName("Categories")]
    public IEnumerable<string> CategoryNames { get; set; }

}

View

@model IEnumerable<MyCompareBase.Models.CategoryIndex>

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>

<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
    <th>
        @Html.DisplayNameFor(model => model.Title)
    </th>
    <th></th>
</tr>

  @foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.CategoryNames)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
        @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
        @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
    </td>
</tr>

}

Controller

public ActionResult Index()
    {

        var localDb = db.Categories.Select(c => c.Name);
        var wcf = category.Categories().Select(c => c.Name);

        var all = new HashSet<String>(localDb);
        all.UnionWith(wcf);

        var viewModel = new Models.CategoryIndex
        {
            Title = "Avaliable Product Categories",
            CategoryNames = all.AsEnumerable()
        };

        return View(viewModel);
    }

Upvotes: 0

Views: 110

Answers (2)

ACS
ACS

Reputation: 453

Valin is right that you need to pass IEnumerable. You can modify your code as:

public ActionResult Index()
{
    var localDb = new List<string>{"a", "b"};
    var wcf = new List<string>{"b","c"};

    var all = new HashSet<String>(localDb);
    all.UnionWith(wcf);

    var viewModel = new List<CategoryIndex>
    {
        new CategoryIndex
            {
                Title = "Avaliable Product Categories",
                CategoryNames = all.AsEnumerable()
            }
    };

    return View(viewModel);
}

Upvotes: 0

Valin
Valin

Reputation: 2295

You are sending single CategoryIndex object to view, but your view expects IEnumerable<CategoryIndex>.

Upvotes: 4

Related Questions