ASP.NET MVC 实践 —— 使用弱类型处理sql存储过程中返回的结果

尽管大家都不建议在MVC中使用弱类型,但是在某些应用场景中,我还是希望可以使用存储过程

于是做了一个简易的解决方案,Controller层返回System.Xml.Linq.XElement给View层调用,见代码:

从sql 存储过程 读取数据

        
/// <summary>
        
/// 从sql 存储过程 读取数据--http://www.cnblogs.com/libsource
        
/// </summary>
        
/// <param name="ProcedureName"></param>
        
/// <param name="Params"></param>
        
/// <returns></returns>
        public static XElement GetDataFromProcedure(string ProcedureName, ListDictionary Params)
        {
            SqlConnection sqlConnection 
= new SqlConnection(global::System.Configuration.ConfigurationManager.ConnectionStrings["HBDEWebConnectionString"].ConnectionString);

            SqlCommand cmd 
= new SqlCommand();

            cmd.CommandText 
= ProcedureName;
            cmd.CommandType 
= CommandType.StoredProcedure;
            cmd.Connection 
= sqlConnection;

            
if (Params != null)
            {
                
foreach (DictionaryEntry entry in Params)
                {
                    
string key = "@" + entry.Key;
                    cmd.Parameters.AddWithValue(key, entry.Value);
                }
            }

            XmlDocument xmldom 
= new XmlDocument();
            
string xmltext="";
            
try
            {

                SqlDataAdapter myAdapter 
= new SqlDataAdapter(cmd);
                DataSet ds 
= new DataSet();
                myAdapter.Fill(ds);  
                xmltext
=ds.GetXml();
            }
            
catch
            {
                
throw;
            }
            
finally
            {
                sqlConnection.Close();
            }
            
return XDocument.Parse(xmltext).Root;
        }

 

Action返回XElement
        //Action返回XElement--http://www.cnblogs.com/libsource
        public ActionResult Test()
        {
            ListDictionary prms 
= new ListDictionary();
            prms.Add(
"ClassTableName""ArticleClass");
            
return View(CommonService.GetDataFromProcedure("P_GetClassInfo", prms));
        }

 

View-ASPX中遍历XElement
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<System.Xml.Linq.XElement>" %>

<%@ Import Namespace="System.Xml.Linq" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    View
-ASPX中遍历XElement--http://www.cnblogs.com/libsource
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    
<h2>
        Test
</h2>
    
<% foreach (var item in Model.Elements("Table"))
       {
%>
    
<%= item.Element("ClassCode"%>:<%= item.Element("ClassName"%>
    
<%%>
</asp:Content>

 

 

posted @ 2009-12-23 17:05  lib  阅读(1889)  评论(0编辑  收藏  举报