I'm using a foreach to loop through an IList of objects in a Partial View in ASP.NET MVC.
Here's the entire code (Message is one of my classes from the Model).
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IList<Message>>" %>
<%
if (ViewData.Model.Count > 0)
{
foreach (MvcTest.Models.Message m in ViewData.Model)
{
Response.Write(m.RenderHtml());
}
}
%>
For some reason, this generates a CS0165 on the ResponseWrite - complaining that m may not be initialised.
I rewrote it like this:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IList<Message>>" %>
<%
//Can't see why I have to declare this as a variable, but I get CS0165 if I use ViewData.Model directly in the foreach
IList<MvcTest.Models.Message> messages = ViewData.Model;
if (messages.Count > 0)
{
foreach (MvcTest.Models.Message m in messages)
{
Response.Write(m.RenderHtml());
}
}
%>
开发者_开发技巧
ie explicitly declaring a variable for the IList rather than just using the (strongly-typed) Model, and it works fine.
Can anyone explain why what I did fixes the problem?
Try changing the Inherits
declaration to
Inherits="System.Web.Mvc.ViewUserControl<System.Collections.Generic.IList<MvcTest.Models.Message>>"
I'm not sure whether it will help, though.
精彩评论