ASP.NET MVC:尝试将变量传递给另一个操作/方法

时间:2019-04-04 07:05:53

标签: c# asp.net-mvc variables asp.net-mvc-controller

我来自Classic ASP背景。我只是想在顶部声明一个变量int TOTAL_ROWS,在知道底部MySQL数据库中有多少行之后,我将其分配给该变量并将值传递给另一个Action /使用的方法。但是我不断得到这个An object reference is required for the non-static field我是OOP的初学者。请帮忙。

代码

namespace BRO.Controllers
{
    public class PasswordController : Controller
    {
        int TOTAL_ROWS;

        //private const int TOTAL_ROWS = 2;
        private static readonly List<DataItem> _data = CreateData();

    private static List<DataItem> CreateData()
    {

        List<DataItem> list = new List<DataItem>();

        string mainconn = ConfigurationManager.ConnectionStrings["MySQLConnection"].ConnectionString;
        MySqlConnection mysqlconn = new MySqlConnection(mainconn);
        string sSQL = " SELECT * FROM mainpass ";
        MySqlCommand comm = new MySqlCommand(sSQL);
        comm.Connection = mysqlconn;

        MySqlDataAdapter adapter = new MySqlDataAdapter(comm);
        DataTable dt = new DataTable();
        adapter.Fill(dt);

        //===Try 1 Not working === An object reference is required for the non-static field,
        //============ method, or property ControllerBase.TempData
        TempData["TOTAL_ROWS"] = dt.Rows.Count;

        int iTOTAL_ROWS = dt.Rows.Count;
        //===Try 2 Not Working=== An object reference is required for the non-static field,
        //============ method, or property PasswordController.TOTAL_ROWS
        TOTAL_ROWS = iTOTAL_ROWS; //=== 

    public ActionResult AjaxGetJsonData(int draw, int start, int length)
    {
        string search = Request.QueryString["search[value]"];
        int sortColumn = -1;
        string sortDirection = "asc";
        if (length == -1)
        {
            length = TOTAL_ROWS; //*** Pass the value here
        }

        // note: we only sort one column at a time
        if (Request.QueryString["order[0][column]"] != null)
        {
            sortColumn = int.Parse(Request.QueryString["order[0][column]"]);
        }
        if (Request.QueryString["order[0][dir]"] != null)
        {
            sortDirection = Request.QueryString["order[0][dir]"];
        }

        DataTableData dataTableData = new DataTableData();
        dataTableData.draw = draw;
        dataTableData.recordsTotal = TOTAL_ROWS; //**** Pass the value here
        int recordsFiltered = 0;
        dataTableData.data = FilterData(ref recordsFiltered, start, length, search, sortColumn, sortDirection);
        dataTableData.recordsFiltered = recordsFiltered;

        return Json(dataTableData, JsonRequestBehavior.AllowGet);
    }

1 个答案:

答案 0 :(得分:1)

您必须将TOTAL_ROWS设为静态变量。只有这样,您才可以通过静态方法进行设置。

但是,如果一次由多个用户使用您的系统,这样做会产生另一个问题。用户数据会重叠-并发问题。

如果您只想将数据从一个动作传递到另一个动作,则请查看Asp.net MVC hereTempData对象的使用。