【问题标题】:How can I display stored procedure results in my MVC view?如何在我的 MVC 视图中显示存储过程结果?
【发布时间】:2018-01-02 02:35:56
【问题描述】:

我找不到任何适用于 Visual Studio 2017 的更新答案。我被困了一天多,试图弄清楚,我在网上找到的每个指南要么非常过时,要么我尝试申请的任何内容我的代码给了我无法修复的错误。我正在使用 C#、HTML5、ASP.NET MVC5 和 VS2017

首先,我的控制器通过以下方式连接到 SQL Server 数据库:

public void GetStoredProc()
{
    Exclusion objExclusion = new Exclusion();

    string StrConnectionString = ConfigurationManager.ConnectionStrings["EligibilityContext"].ConnectionString;

    SqlConnection sqlConnection1 = new SqlConnection(StrConnectionString);

    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "[advantage].[GetAdvantageEligibilityDataOverride]";
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Connection = sqlConnection1;

    sqlConnection1.Open();

    SqlDataReader reader = cmd.ExecuteReader();

    if (reader.HasRows)
    {
        int count = reader.FieldCount;

        while (reader.Read())
        {
            if (count > 3)
            {
                int IntNum;
                int.TryParse(reader.GetValue(0).ToString(), out IntNum);
                objExclusion.PolicyNo = IntNum;
                objExclusion.PolicyMod = (reader.GetValue(1).ToString());
                objExclusion.InsuredName = (reader.GetValue(2).ToString());
                objExclusion.ClientID = IntNum;                   
                //Console.WriteLine(reader.GetValue(i));
            }
        }
    }

    // Data is accessible through the DataReader object here.
    sqlConnection1.Close();
}

这是我的index.html 页面。我知道这里需要添加代码才能显示网页,但我是一个编程菜鸟,不知道该放什么。

@model IEnumerable<Advantage_Exclusions_Eligibility.Models.Exclusion>

@{
ViewBag.Title = "Index";
}

<h2>AEE List</h2>

<p>
@Html.ActionLink("Create New", "Create")
</p>
<p>
&nbsp;</p>

<div>
<table class="table">
<tr>
    <th>
        @Html.DisplayNameFor(model => model.PolicyNo)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.PolicyMod)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.InsuredName)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.ClientID)
    </th>
    <th></th>
</tr>

@foreach (var item in Model)
{
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.PolicyNo)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.PolicyMod)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.InsuredName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.ClientID)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.PolicyNo }) |
        @Html.ActionLink("Details", "Details", new { id=item.PolicyNo }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.PolicyNo })
    </td>
</tr>
}
</table>
    <div class="pagination">
        <nav id="AEEPagination" aria-label="Page navigation" 
style="display:none;">
            <ul class="pagination pagination-sm"></ul>
        </nav>
    </div>
</div>

我们将不胜感激任何和所有的帮助!

【问题讨论】:

  • Visual Studio 的版本与你能写什么代码无关,所以这不是排除解决方案的好借口。
  • @MikeMcCaughan 我知道这通常没有什么区别。但是我发现的大多数解决方案都来自 2012 年或更早的版本,并且我在尝试复制它时不断出错。也许它不存在版本差异,也许只是代码格式化的方式。但我始终无法找到有效的解决方案。
  • 您的问题陈述究竟是什么?您是否面临在 View 或其他方式中显示数据的问题?
  • @SivaGopal 如何在视图中显示数据是主要问题。我的研究表明使用 GridView 是最好的选择,因为我的数据会经常变化。但我无法获得任何适用于我的示例 GridView 代码。

标签: c# html sql-server asp.net-mvc


【解决方案1】:

您的方法public void GetStoredProc() 要么需要返回一个模型@model IEnumerable&lt;Advantage_Exclusions_Eligibility.Models.Exclusion&gt;,要么将一个模型作为参数并使用存储过程的结果填充模型。

一个简短的示例可能如下所示:

// Your url, eg. /<controller>/exclusions
public ActionResult Exclusions()
{
    var viewmodel = GetStoredProc();

    // pass your IEnumerable<Exclusion> to the view
    return View(viewmodel);
}

// Note the return type
public IEnumerable<Exclusion> GetStoredProc()
{
    var exclusions = new List<Exclusion>();


    // ... ...

    if (reader.HasRows)
    {
        int count = reader.FieldCount;

        while (reader.Read())
        {
            Exclusion objExclusion = new Exclusion(); // create a new exclusion for each row!
            if (count > 3)
            {
                int IntNum;
                int.TryParse(reader.GetValue(0).ToString(), out IntNum);
                objExclusion.PolicyNo = IntNum;
                objExclusion.PolicyMod = (reader.GetValue(1).ToString());
                objExclusion.InsuredName = (reader.GetValue(2).ToString());
                objExclusion.ClientID = IntNum;                   
                exclusions.Add(objExclusion); // add the exclusion to your result set!
            }
        }
    }

    // Data is accessible through the DataReader object here.
    sqlConnection1.Close();

    return exclusions;
}

在您看来,您还需要进行一些调整。在这种情况下,您的model 是一个 IEnumerable 模型,因此在表头中没有使用 model.PolicyNomodel.PolicyMod 等。假设您的 Exclusion 模型类已经设置了显示名称属性,您只需更改表的标题以使用集合中第一个 Exclusion 模型的这些属性。

<th>
    @Html.DisplayNameFor(model => model.First().PolicyNo)
</th>
<th>
    @Html.DisplayNameFor(model => model.First().PolicyMod)
</th>
<th>
    @Html.DisplayNameFor(model => model.First().InsuredName)
</th>
<th>
    @Html.DisplayNameFor(model => model.First().ClientID)
</th>
<th></th>

我还建议在表格周围进行一些检查,以确保有数据可以显示:

@if (model.Any()) {
    // Show the table
     <th>
        @Html.DisplayNameFor(model => model.First().PolicyNo)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.First().PolicyMod)
    </th>
    // ... 
}

附带说明,将 SQL 连接包装在 using 中是一种很好的做法。我抓住了我能找到的第一个解释here。您甚至可以将 SqlCommandSqlConnection 链接在一起使用:

例如。

using (var conn = new SqlConnection(connectionString)) 
using (var cmd = new SqlCommand())
{
    // Use conn and cmd here.
}

【讨论】:

  • 你好@njenson!谢谢您的答复。我认为它帮助我走上了正确的轨道。但是,在我添加了 IEnumerable 及其所有代码后,我在“GetStoredProc()”下遇到了一个错误。它说并非所有代码路径都被使用。我该如何使用它?因为没有 HTML 代码,应用程序仍然不会显示任何内容,对吧?
  • @RoshaanKhan 听起来您在GetStoredProc() 末尾缺少return exclusions; 声明
  • 所以我添加了您所说的所有内容,即使我确实有“退货排除”,仍然存在一些错误;这是错误之一。因此,除了“GetStoredProc()”之外,并非所有代码路径都被使用。在 return 关键字上有另一个错误下划线,说“ExclusionsController.GetStoredProc() 返回 void,return 关键字后面不能跟对象表达式。我也有一些关于 HTML 问题的警告,但我想我可以修复一次这已经解决了。
  • 仔细看我贴的代码。错误消息指出该方法返回 void。您会在我的回答中看到 GetStoredProc() 现在必须返回您的视图所期望的模型类型,例如。 public IEnumerable&lt;Exclusion&gt; GetStoredProc() 而不是 public void GetStoredProc()
  • 哦,好吧,我对它的订购方式有些困惑,这是我的错。所以我已经完全调试了我的控制器,现在我的应用程序在 HTML 上崩溃了。它首先不允许“@if (model.Any()) {”所以我删除它只是为了尝试让应用程序工作。现在它在模型 [0] 上出现了错误,声称 [] 不能与类型 IEnumerable 一起使用。
【解决方案2】:

我之前使用过类似的代码。 首先在Controller中创建一个动作。然后使用 ADO.net 运行存储过程。 您可以使用SqlParameter[] 将参数传递给您的存储过程。

控制器代码:

public ActionResult MyResult()
{
    string userid = User.Identity.GetUserId();
    string constr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
    using (SqlConnection conn = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("My_Result", conn))
        {
            conn.Open();
            cmd.CommandType = CommandType.StoredProcedure;

            DataSet ds = new DataSet();
            SqlParameter[] prms = new SqlParameter[1];
            prms[0] = new SqlParameter("@Userid", SqlDbType.VarChar, 500);
            prms[0].Value = userid;
            cmd.Parameters.AddRange(prms);
            SqlDataAdapter ad = new SqlDataAdapter(cmd);
            ad.Fill(ds);

            conn.Close();

            return View(ds);
        }
    }
}

这样,您将从存储过程中检索到的所有记录存储到 DataSet 中。现在返回视图以及数据集数据。

现在在视图中,您需要将这些记录显示到一个表格中。

查看代码

@using System.Data
@model DataSet

@{
    ViewBag.Title = "MyResult";
}

<h2 style="text-align:center;">Result History</h2>

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>

    <style>
        table{
            width:75%;
            text-align:center;
        }
        th,td,tr{
            border:1px solid black;
            text-align:center;
            padding:20px;
        }
    </style>

</head>
<body>
    <table>
        <tr>

            <th>UserName</th>
            <th>ExamDate</th>
            <th>Score</th>
        </tr>
        @foreach (DataRow row in Model.Tables[0].Rows)
        {
            <tr>

                <td>@row["UserName"]</td>
                <td>@row["ExamDate"]</td>
                <td>@row["Score"]</td>
            </tr>
        }
    </table>
</body>
</html>

现在从存储过程中检索到的所有数据都将显示在 View 中的表中。

【讨论】:

    【解决方案3】:

    我们还可以通过以下方式简化视图..!

       @using System.Data;
       @model DataSet
       <center>
       <h2>Result History</h2>
       <table class="table table-bordered table-responsive table-hover">
            <tr>
                <th>UserName</th>
                <th>ExamDate</th>
                <th>Result</th>
            </tr>
        @foreach(DataRow d in Model.Tables[0].Rows)
        {
       <tr>
        <td>@d["UserName"]</td>
        <td>@d["ExamDate"]</td>
        <td>@d["Result"]</td>
       </tr>
     }
     </table>
    </center>`
    

    【讨论】:

      猜你喜欢
      • 2016-08-07
      • 2013-06-08
      • 2017-06-09
      • 1970-01-01
      • 2020-04-18
      • 1970-01-01
      • 1970-01-01
      • 2014-05-23
      • 1970-01-01
      相关资源
      最近更新 更多