且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-05 23:38:04

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

If using EF is not a necessity you can do it in the following way:

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.

If you need to use Entity Framework check out this discussion. Also you want to use the Stored Procedures for Inserting, Updating and deleting check out this tutorial from Microsoft.

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

To execute the code from a button click you can create a form an place just one button inside the form like this:

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

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

And in your controller you would have a TestAction method like this

public ActionResult TestAction(){....}

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

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

if you need to pass any arguments to TestAction, just specify them as parameters in the method and then use the overloaded version of BeginForm that accepts actionName, controllerName, routeValues and formMethod as arguments.

To pass the results to a view you need to create a view model with properties according to the values you recieve from the stored procedure and then, return a view with the view model from the TestAction method.