简体   繁体   中英

Null Object Exception in MVC Partial View

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM