Object reference not set to object instance - Partial View

I have a strongly typed partial view that gives me an "Object reference not set to an instance of an object" error when starting the main view. I know I am not passing in any parameters yet, but is there a way to handle this error?

Master View:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Test Form
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<div id="partial">
<% Html.RenderPartial("DisplayPartial"); %>
</div>

</asp:Content>

      

Partial view:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Student.Models.vwStudent>>" %>

<% foreach (var item in Model) {
           if (item == null) continue; %>

        <tr>            
            <td>
                <%: item.Item1%>
            </td>
            <td>
                <%: item.Item2%>
            </td>
        </tr>

    <% } %>

    </table>

      

0


source to share


2 answers


If you need to render this partial view when you don't have a model, you can of course check that the model is not null before the foreach loop



if (Model != null)
    foreach (...)

      

+1


source


You need to pass some model to your partialView because it needs an instance IEnumerable<Student.Models.vwStudent>

<% Html.RenderPartial("DisplayPartial", model); %>

      



Or you can check your partial view if the model is not null.

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Student.Models.vwStudent>>" %>


<% if (Model != null) {
     foreach (var item in Model) {
           if (item == null) continue; %>

        <tr>            
            <td>
                <%: item.Item1%>
            </td>
            <td>
                <%: item.Item2%>
            </td>
        </tr>

    <% }
} %>

    </table>

      

+2


source







All Articles