gpt4 book ai didi

c# - 在 Controller 内部调用 void 函数

转载 作者:行者123 更新时间:2023-11-29 03:52:04 25 4
gpt4 key购买 nike

我有以下 Controller :

public ActionResult delete(int id)
{
//call function
return RedirectToAction("Index");
}

这里我想从我的模型中调用以下函数:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySql.Data.MySqlClient;

namespace project1.Models.Admin
{
public class delete
{
public void delete(int id)
{
//xxx
const string ConnStr = "...";

MySqlConnection connection = new MySqlConnection(ConnStr);
connection.Open();
MySqlCommand sqlcmd2;
sqlcmd2 = connection.CreateCommand();
sqlcmd2.CommandText = "UPDATE `user` SET Aktive = 0 WHERE Nr = @id;";

sqlcmd2.Parameters.Add("@id", MySqlDbType.Int32).Value = id;

sqlcmd2.ExecuteNonQuery();

connection.Close();
//xxx
}

}
}

我收到此上下文中不允许使用“void”的错误。有没有其他方法可以在这里调用我的函数,或者我应该将整个连接(在“xxx”内)放入我的 Controller ?

最佳答案

更改方法名;

public void deleteFunc(int id)

编辑

首先,您应该注意命名约定。我将您的类名更改为 DeleteAction 和方法名 DeleteRecord

public class DeleteAction
{
public void DeleteRecord(int id)
{
//xxx
const string ConnStr = "...";

MySqlConnection connection = new MySqlConnection(ConnStr);
connection.Open();
MySqlCommand sqlcmd2;
sqlcmd2 = connection.CreateCommand();
sqlcmd2.CommandText = "UPDATE `user` SET Aktive = 0 WHERE Nr = @id;";

sqlcmd2.Parameters.Add("@id", MySqlDbType.Int32).Value = id;

sqlcmd2.ExecuteNonQuery();

connection.Close();
//xxx
}

}

然后,您可以通过从类创建实例来调用所需的函数;

public ActionResult delete(int id)
{
var deleteActionObject = new DeleteAction();
deleteActionObject.DeleteRecord(id);
return RedirectToAction("Index");
}

关于c# - 在 Controller 内部调用 void 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48207639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com