Click here to Skip to main content
15,072,776 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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
HTML
<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

C#
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
C#
@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>


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?
Posted
Updated 4-May-17 1:52am

1 solution

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.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900