I'm having trouble with null reference in asp.net repeater control. The repeater iterates through an IEnumerable<T>
of a class with referenced properties. I have the following classes:
public class SubTarget
{
public int Id { get; set; }
public string Name { get; set; }
public int? ModelId { get; set; }
public virtual Model Model { get; set; }
}
public class Model
{
public int Id { get; set; }
public string Name { get; set; }
public Model()
{
SubTargetTypes = new HashSet<SubTargetType>();
}
}
And repeater control:
<asp:Repeater
runat="server" ItemType="SubTarget" SelectMethod="GetSubTargets">
<ItemTemplate>
<div>
<table>
<tr>
<td><%# Item.SubTargetType.Name %></td>
<td><%# Item.Model.Name %></td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:Repeater>
The problem is: Model
property on SubTarget
is optional. So when ModelId
is null, the references to properties on Model
obviously can't be found. The repeater control correctly handles the null ModelId
when called with just <%# Item.Model %>
and leaves the space empty, but when calling <%# Item.Model.Name %>
I get a null reference exception.
Any ideas how to display just blank space when Foreign key is not set?
Try this :
<td><%# Item.Model !=null ? Item.Model.Name : string.Empty %></td>
I hope help you. :)
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.