[英]ASP.NET MVC - call the same stored procedure from a different view/controller
I have 5 different controllers / models / views. 我有5个不同的控制器/模型/视图。 I have a button on each one of these views that will call a stored procedure.
我在这些视图的每个视图上都有一个按钮,它将调用存储过程。 Depending on the controller, a different parameter is passed to the stored procedure.
根据控制器的不同,会将不同的参数传递给存储过程。
I know how to call this stored procedure from each model class, and then use it in the view and controller. 我知道如何从每个模型类调用此存储过程,然后在视图和控制器中使用它。 I do not know how to create and use this stored procedure as common functionality.
我不知道如何创建和使用此存储过程作为通用功能。
Here's a snippet of what I did - in each model class, I used ADO.NET Entity data model to get the stored procedure into the model. 这是我所做的摘要-在每个模型类中,我都使用ADO.NET实体数据模型将存储过程放入模型中。
In each view, I have: 在每种视图中,我都有:
<p style="margin-left: 2.5em">
<br />
<input type="button" style="height:40px; width: 160px;font-weight: bold;background-color:#00ffff; " value='@("Push to use stored procedure" )' onclick=" if (confirm ('Are you sure you want to do this?')){ window.location.href='@Url.Action("SPROCButton", "Controller1")' ;} " />
</p>
In controller1: 在controller1中:
public ActionResult SPROCButton()
{
try
{
db.uspCallTables("MyDB.temp.Table1");
return RedirectToAction("Index");
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
In other controllers, the only line that changes is the parameter. 在其他控制器中,唯一更改的行是参数。 Is it necessary to have this stored procedure in each model and then call it?
是否有必要在每个模型中都有此存储过程,然后再调用它?
Thank you MR 谢谢MR
There are several ways to solve this. 有几种解决方法。 I propose to create a base controller and add all the common code.
我建议创建一个基本控制器并添加所有通用代码。
The power of inheritance will not be seen in all its splendor in this example, but I think it will help you a lot to write common code. 在此示例中,继承的强大功能不会一目了然,但是我认为它可以帮助您编写通用代码。
public class BaseController : Controller
{
public void callSP(string theParameter){
db.uspCallTables(theParameter);
}
}
then, your Controller1 , as follows: 然后,您的Controller1如下:
public class Controller1 : BaseController
{
public ActionResult SPROCButton()
{
try
{
callSP("MyDB.temp.Table1");
return RedirectToAction("Index");
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
That way you 'll can add all common code in the parent class (BaseController.cs). 这样,您将可以在父类(BaseController.cs)中添加所有通用代码。 I want to clarify that I'm assuming that "db" contains the database context.
我想澄清一下,我假设“ db”包含数据库上下文。 For this to work for you, you must load the object "db" of the new BaseController class in the same way you did in your Controller1.
为此,您必须以与在Controller1中相同的方式加载新BaseController类的对象“ db”。 I hope this help you.
希望对您有帮助。 Let me know it!
让我知道! Regards.
问候。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.