Reputation: 467
Answered
Dbaseman was correct but to simplify it all, I don’t need a modal and my code looks like this now:
[ChildActionOnly]
public ActionResult RecentNews()
{
return PartialView(db.Articles.ToList());
}
and
@{Html.RenderAction("RecentNews");}
Below is my old code that wasn’t working
I’m having trouble getting the following to work, I’m unsure if I’m even close to being on the right track or not. The code all works fine if I create a View but not if I create a partial View and add it to other views. Whatever I try I seem to get the error : Object reference not set to an instance of an object.
In my view I have:
@Html.Partial("RecentNews")
My action looks like this:
public ActionResult RecentNews()
{
var rn = (from m in db.Articles
select new RecentNews
{
ArticleHeading = m.ArticleHeading
});
return View(rn);
//return View(db.Articles.ToList());
}
My modal:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace melbournesportsstadium.Models
{
public class RecentNews
{
public string ArticleHeading { get; set; }
}
}
And my RecentNews.cshtml:
@model List<melbournesportsstadium.Models.RecentNews>
<table>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.ArticleHeading)
</td>
</tr>
}
</table>
Can someone please help me get this working?
Upvotes: 2
Views: 7722
Reputation: 102753
You're getting "null reference" because the partial view is not receiving any model; @Html.Partial doesn't return to the controller, it renders the view directly. Change it to @Html.Action("RecentNews") and it should work.
Upvotes: 2