In order to simplify your code you should utilize the Null Object pattern. Instead of using null to represent a non existing value, you use an object initialized to empty/meaningless values. This way you do not need to check in dozens of places for nulls and get NullReferenceExpections in case you miss it.
The primary difference between the two methods is that Partial generates the HTML from the View and returns it to the View to be incorporated into the page. RenderPartial, on the other hand, doesn't return anything and, instead, adds its HTML directly to the Response object's output.
RenderPartial returns void. Html. Partial injects the html string of the partial view into the main view. Html. RenderPartial writes html in the response stream.
You can render the partial view in the parent view using the HTML helper methods: @html. Partial() , @html. RenderPartial() , and @html. RenderAction() .
Andrew I think the problem you are getting is a result of the RenderPartial method using the calling (view)'s model to the partial view when the model you pass is null.. you can get around this odd behavior by doing:
<% Html.RenderPartial("TaskList", Model.Tasks, new ViewDataDictionary()); %>
Does that help?
@myandmycode's answer is good, but a slightly shorter one would be
<% Html.RenderPartial("TaskList", new ViewDataDictionary(Model.Tasks)); %>
This works because the ViewDataDictionary
is the thing that holds the model, and it can accept a model as a constructor parameter. This basically passes an "entire" view data dictionary, which of course only contains the possibly-null model.
It appears that when the property of the Model you're passing in is null MVC intentionally reverts back to the "parent" Model. Apparently the MVC engine interprets a null model value as intent to use the previous one.
Slightly more details here: ASP.NET MVC, strongly typed views, partial view parameters glitch
If you do not want to loose your previous ViewData in the partial view, you could try:
<% Html.RenderPartial("TaskList", Model.Tasks, new ViewDataDictionary(ViewData){Model = null});%>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With