强类型模型/需要输出模型格式

时间:2011-09-24 20:09:03

标签: asp.net-mvc-2

实际上我是这项技术的新手,我使用的是mvc2架构。我无法将模型中的数据加载到查看页面。我使用了强类型模型EventListing.Models.EventInfo。我需要模型格式的输出。我该如何使用我的选择功能

模型

public class EventInfo  
    {            
        public int OPR { get; set; }
        public int EVENT_ID { get; set; }
        public string  SUBSITE { get; set; }
public static DataTable Select()
        {
            DataTable myDataTable = new DataTable();
            Dbhelper DbHelper = new Dbhelper();
            DbCommand cmd = DbHelper.GetSqlStringCommond("SELECT * FROM WS_EVENTINFO");
            myDataTable.Load(DbHelper.ExecuteReader(cmd));
            return myDataTable;
        }

控制器

public ActionResult List()
        {            
            return View(EventModel.EventList());
        }

查看

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<EventListing.Models.EventInfo>" %>
<% foreach (var model in EventListing.Models.EventModel.EventList())
                   { %>
                <tr>
                    <td>
                        <%= Html.ActionLink(model.TITLE, "Detail", new { id = model.EVENT_ID })%>

1 个答案:

答案 0 :(得分:1)

让我尝试清理一下你的代码:

public class EventInfo  
{            
    public int OPR { get; set; }
    public int EVENT_ID { get; set; }
    public string SUBSITE { get; set; }

    ... some other properties that you might want to use

    public static IEnumerable<EventInfo> Select()
    {
        var helper = new Dbhelper();
        using (var cmd = helper.GetSqlStringCommond("SELECT * FROM WS_EVENTINFO"))
        using (var reader = helper.ExecuteReader(cmd))
        {
            while (reader.Read())
            {
                yield return new EventInfo
                {
                    OPR = reader.GetInt32(reader.GetOrdinal("OPR")),
                    EVENT_ID = reader.GetInt32(reader.GetOrdinal("EVENT_ID")),
                    SUBSITE = reader.GetString(reader.GetOrdinal("SUBSITE"))
                }
            }
        }
    }
}

然后在控制器动作中:

public ActionResult List()
{
    var model = EventInfo.Select().ToList();
    return View(model);
}

最后在视图中:

<%@ Page 
    Language="C#" 
    Inherits="System.Web.Mvc.ViewPage<IEnumerable<EventInfo>>" %>

<% foreach (var item in Model) { %>
<tr>
    <td>
        <%= Html.ActionLink(item.TITLE, "Detail", new { id = item.EVENT_ID }) %>
    </td>
...

应该对此进行的下一个改进是将数据访问(Select静态方法)外部化到一个单独的存储库中,让控制器使用此存储库,而不是直接调用Select方法来查询数据库。