문제

Partial view does not return any data.When i check with debug tool on PartialView page(_ContentBlock.cshtml), model seem to null.

Controller

public ActionResult Module()
{
    int RouteDataValue = default(int);
    if (RouteData.Values["id"] != null)
    {
        RouteDataValue = int.Parse(RouteData.Values["id"].ToString());
    }

    using (Models.ContentModel db = new Models.ContentModel())
    {
        var Query = from n in db.PageModule
                       join m in db.Module on n.ModuleId equals m.ModuleId
                       where n.PageId == RouteDataValue
                       select m.PhysicalPath;

        return PartialView(Query.Single()); //returns PartialView such as ~/Modules/Content/_ContentBlock.cshtml
    }
}

public PartialViewResult ContentBlock()
{
    using (Models.ContentModel db = new Models.ContentModel())
    {
        return PartialView("~/Modules/Content/_ContentBlock.cshtml", db.ContentBlock.Where(n => n.PageId == 2).Single());
    }
}

Page.cshtml

@Html.Action("Module")

_ContentBlock.cshtml

@model IEnumerable<Models.ContentBlock>
@foreach (var item in Model)
{
    @Html.DisplayFor(n => item.Content)
}
도움이 되었습니까?

해결책

You seem to have used the Html.Partial helper instead of Html.Action. So you were basically only rendering the partial without ever hitting the controller action that is supposed to populate and the model to the partial.

다른 팁

Your page Page.cshtml is calling the partial view action Module using:

@Html.Action("Module")

The action called Module is being executed. In that action, your query results in a path to your view, such as:

"~/Modules/Content/_ContentBlock.cshtml"

That action is returning the single result of that query using:

return PartialView(Query.Single());

What this is doing is passing the name of the view to the PartialView method to return which view is going to be used to display data from the action. In addition, no model data is included in this return.

That's where your problem is. When you return the path to the partial view, you are simply telling the MVC system what view to use to display the data from Module. It won't actually call another partial view. That's not how it works. So your model is null because, you didn't pass any data in your PartialView(...) call.

You have another action called ContentBlock. But that action is not being called because nothing is calling it.

Edit:

Another problem you have is that _ContentBlock.cshtml uses a model of IEnumerable<ContentBlock>, but you're only passing it a .Single() from your ContentBlock action.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top