I have the following template fields in my gridview (ItemType attribute is set properly: ItemType="gEchoLu.Model.DiscussionTimeframe"
):
<asp:TemplateField HeaderText="Discussion Wall">
<ItemTemplate>
<asp:Label runat="server" ID="lbl_Discussion" Text="<%#Item.DiscussionWall.WallTitle %>"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Course">
<ItemTemplate>
<asp:Label runat="server" ID="lbl_Discussion" Text="<%#Item.DiscussionWall.Course.CourseTitle %>"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
The first field is displayed correctly. However, the second template field is always null. Here is the code by which I bind data to the gridview:
gEchoLuDBContext db = new gEchoLuDBContext();
var timeframes = db.Timeframes.Include(c => c.DiscussionWall.Course).Where(tf => tf.CreatedBy == userid).ToList();
grd_Timeframes.DataSource = timeframes;
grd_Timeframes.DataBind();
When I debug it, the properties of Course is null actually. In my model, each TimeFrame
belongs to a DiscussionWall
, and each DiscussionWall
belongs to a Course
. However, there is no direct relationship between a TimeFrame
and a Course
. I am not sure if what I want is doable in this situation. Do I have to define a (1-to-many) relationship between TimeFrame
an DiscussionWall
entities to achieve what I want? (I know this can be done by using OnDataBound
, but I wonder if ItemType
can be used to handle this quickly).
Here are the related parts of my model:
public class DiscussionWall
{
[Key]
public int WallId { get; set; }
[Required]
[StringLength(200)]
public string WallTitle { get; set; }
[Required]
[ForeignKey("Course")]
public int CourseId { get; set; }
private Course _course;
public Course Course
{
get { return _course?? (_course = new Course());}
set { _course = value; }
}
public List<DiscussionTimeframe> Timeframes { get; set; }
}
public class DiscussionTimeframe
{
public int DiscussionTimeframeId { get; set; }
[Required]
public string TimeFrameName { get; set; }
public int DiscussionWallId { get; set; }
[ForeignKey("DiscussionWallId")]
public DiscussionWall DiscussionWall { get; set; }
}
public class Course
{
public int CourseId { get; set; }
public string CourseTitle { get; set; }
public List<DiscussionWall> DiscussionWalls { get; set; }
}
It worked when I change this:
private Course _course;
public Course Course
{
get { return _course?? (_course = new Course());}
set { _course = value; }
}
into this:
public Course Course
{
get;
set;
}
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.