通过多个局部视图传递多个模型进行查看 [英] Pass multiple model to view with several partial view

查看:74
本文介绍了通过多个局部视图传递多个模型进行查看的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的索引视图包含多个局部视图

在每个局部视图中我想显示添加到数据库的最新项目



< b>我尝试了什么:



i在我的主索引中创建几个部分并添加部分

i have index view that contain several partial view
in each partial view i want to show latest item added to database

What I have tried:

i create several section in my main index and add partial to it

<section class="news">
            <h1 class="tit">Last News</h1>
            <section class="line"></section>
            @Html.Partial("_NewsPartialView")
</section>

<section class="downloads">
            <h1 class="tit">Last PC sofwtare </h1>
            <section class="line"></section>
            @Html.Partial("_LastSoftwarePartialView")
</section>

<section class="downloads">
            <h1 class="tit">Last Android sofwtare </h1>
            <section class="line"></section>
            @Html.Partial("_LastAndroidSoftwarePartialView")
</section>




控制器中的
我为每个局部视图添加了几种操作方法





in controller i add several action method for each partial view

public PartialViewResult _NewsPartialView()
       {
           return PartialView(db.Newses.Take(5).ToList());
       }

public PartialViewResult _LastSoftwarePartialView()
       {
           return PartialView(db.software.Take(5).ToList());
       }

public PartialViewResult _LastAndroidSoftwarePartialView()
       {
           return PartialView(db.DroidSoftware.Take(5).ToList());
       }



这是我的意见之一


and here is one of my parital view

@model IEnumerable<Myapp.Models.News>


<section class="content-part">
@foreach (var item in Model)
{
    <section class="newbook-content">
      @Html.DisplayFor(modelItem => item.NewsTitle)


    @Html.DisplayFor(modelItem => item.NewsSummery)


    @Html.DisplayFor(modelItem => item.NewsPublishTime)


    @Html.DisplayFor(modelItem => item.NewsBody)


    @Html.ActionLink("Details", "Details", new { id = item.NewsId })
    </section>
}
</section>





但我得到System.NullReferenceException:对象引用没有设置为对象异常的实例

我也不想使用viewmodel

如果有任何方法在每个局部视图渲染时调用action方法?



but i get System.NullReferenceException: Object reference not set to an instance of an object exception
also i dont want to use viewmodel
if there any way to call action method when each partial view rendered?

推荐答案

Html.Partial直接注入视图,它不会调用控制器上的操作,因此部分视图中的模型都为null。如果你想注入一个动作的结果,请使用Html.Action或Html.RenderAction(谷歌的差异,有很多文章可以解释这一点)。这将调用您的操作,该操作将依次返回正确的局部视图,并填充模型。
Html.Partial is injecting the view directly, it isn't calling the action on your controller so the model in your partial views are all null. If you want to inject the result of an action use Html.Action or Html.RenderAction instead (google for the difference, there are lots of articles that explain this). That will call your action which will in turn return the right partial view with the model populated.


这篇关于通过多个局部视图传递多个模型进行查看的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆