Object reference not set to an instance of an object - Partial View

倾然丶 夕夏残阳落幕 提交于 2019-11-28 12:46:00

问题


I have a strongly typed partial view which is giving me "Object reference not set to an instance of an object" error when I launch the master 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>

回答1:


If you need to render this partial view when you don't have a Model, you can certainly test that Model is not null before the foreach loop

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



回答2:


You have to pass some Model to your partialView, because it need a instance of IEnumerable<Student.Models.vwStudent>

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

Or, you can check in 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>


来源:https://stackoverflow.com/questions/11419753/object-reference-not-set-to-an-instance-of-an-object-partial-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!