开发者

strongly typed model /need output in model format

actually i'm new to this technology, i am using mvc2 architecture. l cant able to load the data from my model to view page. i used strongly typed model EventListing.Models.EventInfo. i need output in model format. how can i use my select function

Model

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");
            myDataTa开发者_开发百科ble.Load(DbHelper.ExecuteReader(cmd));
            return myDataTable;
        }

Controller

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

View

<%@ 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 })%>


Let me try to clean up your code a little:

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"))
                }
            }
        }
    }
}

then in the controller action:

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

and finally in the view:

<%@ 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>
...

The next improvement that should be done to this is to externalize the data access (the Select static method) into a separate repository and have the controller use this repository instead of directly invoking the Select method to query the database.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜