如何在ASP.Net MVC(C#)中调用和执行存储过程

问题描述 投票:0回答:3

大家好,我现在有点茫然。我已经使用 ASP.NET MVC 和 C# 在 Visual Studio 中创建了数据库、模型、控制器和视图,但我不知道如何调用我也创建的存储过程。

我希望在我放置在视图中的按钮上调用存储过程。 单击按钮时,该存储过程应执行并显示结果。 下面是我创建的存储过程、视图、模型和控制器。

这是我的“员工”模型:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace MVCSimpleApp.Models
{
    [Table("Employees")]
    public class Employee
    {
        [Display(Name ="Employee Id")]
        public int EmployeeId { get; set; }
        [Display(Name ="First Name")]
        public string FirstName { get; set; }
        [Display(Name ="Last Name")]
        public string LastName { get; set; }
    }
}

这是我的数据上下文:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace MVCSimpleApp.Models
{
    public class EmployeeContext : DbContext
    {
        public DbSet<Employee> Employee { get; set; }
    }
}

这是我的员工控制器:

using MVCSimpleApp.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace MVCSimpleApp.Controllers
{
    public class EmployeeController : Controller
    {
        private EmployeeContext db = new EmployeeContext();
        // GET: Employee
        public ActionResult Index()
        {

            var employees = from e in db.Employee select e;
            return View(employees);
        }
    }
 }

现在这是我的存储过程。东西不多,只是练习用的东西。

Create Proc DisplayStudents
AS
BEGIN
     /*selecting all records from the table whose name is "Employee"*/
    Select * From Employee
END

这是我的观点:

@model IEnumerable<MVCSimpleApp.Models.Employee>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
 }

 <h2>Student List</h2>

 <p>
    <a href="@Url.Action("Create")" title="Add new" class="btn btn-primary btn-lg">
        <span class="glyphicon glyphicon-plus "></span>
        Add Student
    </a>


</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.EmployeeId)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FirstName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.LastName)
        </th>
        <th></th>
    </tr>

 @foreach (var item in Model) {
 <tr>
    <td>
        @Html.DisplayFor(model => item.EmployeeId)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.FirstName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.LastName)
    </td>
    <td>
        <span>
            <a href="@Url.Action("Edit", new { id = item.EmployeeId})" title="Edit Record">
                <span class="glyphicon glyphicon-pencil"></span>
            </a>
        </span>
        |
        <span>
            <a href="@Url.Action("Details", new { id = item.EmployeeId})" title="View Details">
                <span class="glyphicon glyphicon-th-list"></span>
            </a>
        </span>
        |
        <span>
            <a href="@Url.Action("Delete", new { id = item.EmployeeId})" title="Delete">
                <span class="glyphicon glyphicon-trash"></span>
            </a>
        </span>
    </td>
</tr>
}
  /*this is the button I want the stored procedure to be called on when I click it*/
  <button>Run</button>
</table>

各位,我需要你们对此事的意见和反馈。将接受将参数传递给存储过程的提示。如果我没有在这里做事,请纠正我。谢谢您的关心。

stored-procedures c# visual-studio-2015
3个回答
18
投票

如果不需要使用 EF,您可以通过以下方式进行:

string cnnString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;

SqlConnection cnn = new SqlConnection(cnnString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnn;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "ProcedureName";
//add any parameters the stored procedure might require
cnn.Open();
object o = cmd.ExecuteScalar();
cnn.Close();

如果您需要使用实体框架,请查看此讨论。此外,您还想使用存储过程来插入、更新和删除,请查看 Microsoft 的本教程

要通过单击按钮执行代码,您可以创建一个表单,然后在表单中只放置一个按钮,如下所示:

@using(Html.BeginForm("TestAction", "TestController", FormMethod.Get))
{
    <input type="submit" value="Submit" />
}

在你的控制器中你会有一个像这样的 TestAction 方法

public ActionResult TestAction(){....}

如果您需要将任何参数传递给 TestAction,只需将它们指定为方法中的参数,然后使用接受 actionName、controllerName、routeValues 和 formMethod 作为参数的 BeginForm 的重载版本。

要将结果传递给视图,您需要根据从存储过程收到的值创建一个具有属性的视图模型,然后从 TestAction 方法返回带有视图模型的视图。


0
投票

以下是如何使用实体框架执行此操作的示例。我个人不太喜欢实体框架,因为它又慢又笨重,但数据库经验有限的人往往喜欢它。

通常我喜欢给出包含所有代码的完整示例,但由于实体框架的配置方式,我将传递该部分。请记住,如果没有设置实体框架上下文,这将无法工作。

    private RAP_Entities db = new RAP_Entities();

    public string GetGUID(string DeviceID, string CCCShopID)
    {
        SqlParameter[] Parameters =
        {
            new SqlParameter("@DeviceID", DeviceID),
            new SqlParameter("@CCCShopID", CCCShopID)
        };

        string DistributionChannelGUID = db.Database.SqlQuery<string>("GetDistributionChannelGUID @DeviceID, @CCCShopID", Parameters).ToString();

        return DistributionChannelGUID;   
    }

-2
投票

您可以通过普通 ADO.Net 方法来实现,其中使用

SqlCommand
调用存储过程并向其传递一些参数。

  1. 打开连接。
  2. 创建
    SqlCommand
    的实例,我们需要在其中传递存储过程名称和连接字符串。
  3. CommandType
    表示命令的类型。
  4. 传递过程参数。
  5. SqlDataAdapter
    用于呼叫程序。
  6. da
    将返回结果。按您的要求使用

代码:

try
{       
    conn.Open();
    SqlCommand dCmd = new SqlCommand("store_procedure_name",conn);
    dCmd.CommandType = CommandType.StoredProcedure;
    dCmd.Parameters.Add(new SqlParameter("@parameter2",parameter2));
    dCmd.Parameters.Add(new SqlParameter("@parameter1", parameter1));
    SqlDataAdapter da = new SqlDataAdapter(dCmd);
    DataTable table = new DataTable();
    ds.Clear();
    da.Fill(ds);
    conn.Close();

    var das = ds.Tables[0].AsEnumerable();
    return ConvertToDictionary(ds.Tables[0]);
}
catch
{
}
© www.soinside.com 2019 - 2024. All rights reserved.