I've new to ASP.NET MVC and .NET in general, so just got a simple question. I want to display a list of objects on the web page, what's the best way to do it?
The models so far are as follow:
public class NoticeBoard
{
public List<Notice> Notices;
public NoticeBoard()
{
Notices = new List<Notice>();
}
}
public class Notice
{
public int ID;
public DateTime StartDate;
public DateTime EndDate;
public String Content;
}
So real simple, the controller creates a NoticeBoard object containing a list of notices, and the View needs to display the notices.
I see there're controls like GridView, DataList, DetailsView, ListView. What开发者_高级运维're the differences between them and which one is most suitable for this case?
None of the controls you listed are suitable for MVC. Those are all ASP.Net WebControls, meant for use with a "classic ASP.Net" webforms application. They rely on ViewState and other page lifecycle mechanisms in order to function correctly, and generally will not work with an MVC project.
If you're using ASP.Net MVC, you're dealing with HTML in more of a raw form, rather than using webcontrols. To generate a list of items, add code like this to your view:
<% foreach(var notice in Model.Notices) { %>
<tr>
<td><%= notice.StartDate.ToString() %></td>
<td><%= notice.EndDate.ToString() %></td>
<td><%= notice.Content %></td>
</tr>
<% } %>
If you find that you're using the same code over and over to generate HTML with in your views, consider writing it as an HtmlHelper extension method.
精彩评论