2

I have a partial view called _News that when called by itself works as expected.

When I call it from another view using the following code:

<div>
  @html.Partial("_News");
</div>

It throws this error:

Object reference not set to an instance of an object

At this line of code in the view:

@foreach (var item in Model) {

Where the view is referencing the model. I realise this means that the view is not being passed the model from the Controller but I am perplexed as to why.

The Controller is called NewsController and is located in Controllers. The View is called _News and is located in Shared Views. The view calling the partial view is the default home/index page.

1
  • It is probably due to the fact you're trying to dereference a null reference. Somewhere in the code of your view. Commented Dec 21, 2012 at 7:05

2 Answers 2

3

If your partial needs to access data from the model, you need to pass the model into the Partial() method:

@Html.Partial("_News", Model)

MSDN: http://msdn.microsoft.com/en-us/library/system.web.mvc.html.partialextensions.partial%28v=vs.108%29.aspx

EDIT:

Per your comment below, I think you're actually after this: http://haacked.com/archive/2009/11/17/aspnetmvc2-render-action.aspx - this lets you call a controller action and render the result into the current view.

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

4 Comments

Hi, It uses a completely different model from the view calling it. Does it not get passed the model from its own controller?
The Partial() method does not call a controller action, so no.
Yes, but better to add it to the answer.
2

Could your partial model be a subset or a property of your main views' model? I say could because, to Tieson's point, you can deal with almost any discrepancy between the model the partial wants and the model the view wants... BUT if the model your partial wants is so far disparate from the model your view wants then I will often take that as a possible smell that my two models are not flushed out thoroughly/correctly (basically: "Am I trying to represent too many things or unrelated things on the same page?") .

Additionally, if you can make the model of your partial be a property of the main view's model such that you can pass the model into the partial like this:

@Html.Partial("_News", Model.SomePropertyThatFulfillsTheDataSourceOfThePartial)

then if and when you need to submit the form, this would make model binding much easier as well.

Comments

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.