Html.Action throwing exception: An exception of ty

2019-09-11 07:24发布

问题:

I'm getting this error from @Html.Action("getCategory", "Blogs") in the master layout for my blog.

The error is:

An exception of type 'System.Web.HttpException' occurred in System.Web.dll but was not handled in user code Additional information: Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.

Here is my controller:

public ActionResult getCategory()
    {
        var categories = _repo.getBlogs().Select(c => new
        {
            c.Category
        }).ToList();
        return PartialView("_category", categories);
    }

And here is my partial view:

@model  IEnumerable<MainSite.Data.Blog>

<div class="sw_categories">
<div class="sw_title">
    <h4>Categories</h4>
</div>
<ul class="arrows_list">
    @foreach (var c in Model)
    {
        <li><a href="#">@c</a></li>
    }
</ul>
</div>

I'm pretty new to ASP.NET MVC, so could anyone please explain the error to me and how I could fix this?

回答1:

You'll want to either..

  1. return a collection of Blogs from getCategory(), since that is what your partial is expecting:

    IEnumerable<MainSite.Data.Blog>  
    
  2. or change the model type in the partial to correspond with what you're returning from getCategory(). Example:

    IEnumerable<MainSite.Data.Blog.Category>