簡體   English   中英

如何在 ASP.Net MVC(C#) 中調用和執行存儲過程

[英]How to call and execute stored procedures in ASP.Net MVC(C#)

伙計們,大家好,我在這里有點不知所措。 我已經使用 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>

請伙計們,我需要您對此事的意見和反饋。 將接受將參數傳遞給存儲過程的提示。 如果我沒有在這里做事,請糾正我。 感謝你的關心。

如果不需要使用 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 方法返回帶有視圖模型的視圖。

以下是如何使用實體框架執行此操作的示例。 我個人不是實體框架的忠實粉絲,因為它又慢又笨重,但 DB EXP 有限的人往往喜歡它。

通常我喜歡給出一個包含所有代碼的完整示例,但由於實體框架的配置方式,我將傳遞該部分。 請記住,如果尚未設置實體框架上下文,這將無法工作。

    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;   
    }

您可以通過普通 ADO.Net 方法來實現,在該方法中您使用 SqlCommand 調用 StoredProcedure 並向其傳遞幾個參數。

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
{

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM