2

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks dbaseman, I tried that and it sort of works but for some reason its pulling the partial view in as a complete view with the _layout. do you know why that would be???
@Bojangles Hm. The only places I know of where a layout can be set are 1) in the View itself, 2) web.config in the view's path or a parent path
@Bojangles Sorry, I meant to write _ViewStart.cshtml. Do you have one of those in you project? A default layout might be set there ...
it was quite interesting but return PartialView and [ChildActionOnly] fixed it, thanks for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.