且构网

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

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

更新时间:2023-12-05 23:15:58

如果不需要使用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();

如果您需要使用实体框架,请查看此讨论。您还想使用存储过程进行插入,更新和删除签出本教程,来自微软。

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,只需在方法中将它们指定为参数,然后使用BeginForm的重载版本即可接受actionName,controllerName,routeValues和formMethod作为参数。




要将结果传递给视图,您需要根据从存储过程中接收到的值创建一个具有属性的视图模型,然后返回通过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.