ASP.Net MVC:将视图模型传递给局部视图

时间:2013-11-12 21:16:48

标签: asp.net-mvc razor

我在这里阅读了很多帖子:这个但仍然没有得到它。

我有一个视图,其中部分视图分页控件需要访问与父视图相同的模型。

父视图:

model IEnumerable<Models.ExchangeBrowseViewModel>
@{
    ViewBag.Title = metaExchange.Index_PageTitle;
}
@section styles
{        
    <link rel="stylesheet" type="text/css" href="/incl/css/bp-default.css" />
    <link rel="stylesheet" type="text/css" href="/incl/css/bp-component.css" /> 
    <link rel="stylesheet" type="text/css" href="/incl/css/paging.css" />   
}
<hgroup>
    <h2>@metaExchange.Index_InlineTitle</h2>
    <h3>@ViewBag.Message</h3>
</hgroup>

<div class="container">
    <div class="row">
        <div class="col-md-2" style="border: 1px solid #000000">
             @Html.Partial("_ItemsSearch_BasicPartial");         
        </div>
        <div class="col-md-10">
            @Html.Action("Pagination", new {showWell=false, model=Model});

分页行动:

[AllowAnonymous]
    [ChildActionOnly]
    public ActionResult Pagination(ExchangeBrowseViewModel model, bool showWell)
    {
        ViewBag.ShowWell = showWell;
        return PartialView("_ItemsList_Pagination", model);
    }

分页部分视图

@model IPagedList<Models.ExchangeBrowseViewModel>
<div class="mvcpagination">
    @Html.Raw(Ajax.Pager(
        new Options
            {
                PageSize = Model.PageSize,
                TotalItemCount = Model.TotalItemCount,
                CurrentPage = Model.PageNumber,
                ItemTexts = new ItemTexts() {Next = ">>", Previous = "<<", Page = ""},
                ItemIcon = new ItemIcon() {First = "icon-backward", Previous = "icon-chevron-left", Next = "icon-chevron-right", Last = "icon-forward"},
                TooltipTitles = new TooltipTitles() {Next = "Next", Previous = "Previous", Page = "Page {0}."},
                Size = Size.normal,
                Alignment = Alignment.right,
                IsShowControls = true,
                IsShowFirstLast = true,
                CssClass = "light-theme"
            },
        new AjaxOptions
            {
                UpdateTargetId = "grid-list",
                OnBegin = "beginPaging",
                OnSuccess = "successPaging",
                OnFailure = "failurePaging"
            }, new {controller = "Requests", action = "Index", requestTitle = ViewData["requestTitle"]}))
    @if (ViewBag.ShowWell)
    {
        <div class="well">
            Showing <span class="badge badge-success">@Model.ItemStart</span> to <span class="badge badge-success">@Model.ItemEnd</span>
            of <span class="badge badge-info">@Model.TotalItemCount</span> entries</div>
    }
</div>

问题是模型在action方法中总是为null,因此部分抛出一个尝试访问模型属性的NullReference异常。

1 个答案:

答案 0 :(得分:1)

您在ExchangeBrowseViewModel操作中传递了Pagination,并将其绑定到控制器方法中的错误类型。

您将整个IEnumerable<Models.ExchangeBrowseViewModel>模型从父视图传递到操作,并希望获得ExchangeBrowseViewModel。但是模型绑定器找不到合适的数据,这就是它为空的原因。