从FORM传递参数到存储过程

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从FORM传递参数到存储过程相关的知识,希望对你有一定的参考价值。

我是一个SysAdmin,有些人如何走向发展的位置。但我有一个情况,解决方案可能非常简单,但我在过去3天一直在研究,没有运气。

这是我的问题:我建立了一个存储过程,返回一个报告,其中包含学生在健身房度过的日期和总时间,我需要传递4个参数:

Student ID, StartDate, EndDate, Location

我建立了我的表格。

<div style="margin-top:20px;">
    <form action="/Home/Index" method="Post" name="getreport" class="form-inline">
        <div class="form-group">
            <label for="StudentID">Student ID</label>
            <input type="text" class="form-control" Value="" name="Client" placeholder="xxx-xx-xxxx">
        </div>
        <div class="form-group">
            <label for="StartDate">Start Date</label>
            <input type="date" class="form-control" name="StarDate">
        </div>
        <div class="form-group">
            <label for="EndDate">End Date</label>
            <input type="date" class="form-control" name="EndDate">
        </div>
        <div class="form-group">
            <label for="Location">Location</label>
            <select name="Device" class="form-control">
                <option value="780001">GYM</option>
                <option value="0">Library</option>
                <option value="0">#</option>
                <option value="0">#</option>
            </select>
        </div>
    </form>
</div>

它看起来像这样

enter image description here

这是我的HomeController我的帖子方法:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(reportmodel gen)
    {
        string Client = gen.Client;
        DateTime StartDate = gen.StartDate;
        DateTime EndDate = gen.EndDate;
        int Device = gen.Device;

        return Redirect("/General/General");
    }
}

如您所见,我正在捕获我的帖子数据:

enter image description here

这是我的模型类:

public class reportmodel
{
    public String Client { set; get; }
    public DateTime StartDate { set; get; }
    public DateTime EndDate { set; get; }
    public int Device { set; get; }
}

现在这是我的数据访问层,我需要传递这些参数:

public class Db 
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);

    public DataSet GetReports()
    {
        reportmodel obj = new reportmodel();

        SqlCommand com = new SqlCommand("spReportStudents", con);
        com.CommandType = CommandType.StoredProcedure;

        com.Parameters.Add("@StartDate", SqlDbType.Date).Value = "02/01/2018";
        com.Parameters.Add("@EndDate", SqlDbType.Date).Value = "02/28/2018";
        com.Parameters.Add("@Device", SqlDbType.Int).Value = "780001";
        com.Parameters.Add("@Client", SqlDbType.VarChar, 30).Value = "804369081";

        SqlDataAdapter da = new SqlDataAdapter(com);
        DataSet ds = new DataSet();
        da.Fill(ds);

        return ds;
    }

    public DataSet TotalTime()
    {
        SqlCommand com = new SqlCommand("spTotal", con);
        com.CommandType = CommandType.StoredProcedure;

        com.Parameters.Add("@StartDate", SqlDbType.Date).Value = "02/01/2018";
        com.Parameters.Add("@EndDate", SqlDbType.Date).Value = "02/28/2018";
        com.Parameters.Add("@Device", SqlDbType.Int).Value = "780001";
        com.Parameters.Add("@Client", SqlDbType.VarChar, 30).Value = "804369081";

        SqlDataAdapter da = new SqlDataAdapter(com);
        DataSet ds1 = new DataSet();
        da.Fill(ds1);

        return ds1;
    }
}

正如你们所看到的那样,我现在很难对这些值进行编码

.Value = "02/28/2018" 

但它应该是Value = Client。

我试试

reportmodel obj = new reportmodel();

并添加.Value = obj.Client但这是传递Null值。

这是我的报告控制器实际上命名为GeneralController

DAL.Db dblayer = new DAL.Db();

public ActionResult General()
{
        DataSet ds = dblayer.GetReports();
        ViewBag.general = ds.Tables[0];
        DataSet ds1 = dblayer.TotalTime();
        ViewBag.total = ds1.Tables[0];

        return View();
}

我应该得到这个

enter image description here

我知道答案就在我面前,但我看不到它!

答案

我不确定问题是什么(你说你没有得到想要的结果,但是你得到了什么呢?),但是如果这有帮助,我想我会分享我用于我所有的课程数据库查询:

using System;
using System.Data;
using System.Data.SqlClient;

namespace MyClassLibrary.DB
{
    public class MyDB
    {
        public static System.Configuration.ConnectionStringSettings connString;
        public static SqlConnection conn;
        public static string sSQL;
        public int? InsertedID;
        public string Error;

        public SqlConnection Connection
        {
            get { return conn; }
        }

        private static void SetSQLConn()
        {
            if ((!(conn == null) && conn.State == ConnectionState.Open))
            {
            } else
            {
                connString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnString"];
                conn = new SqlConnection();
                conn.ConnectionString = connString.ConnectionString;
                conn.Open();
            }
        }

        public DataTable QueryResults(string SQL) {
            SetSQLConn();
            sSQL = SQL;
            SqlCommand cmd = new SqlCommand(sSQL, conn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            return dt;
        }

        //Note that all queryResult with parameter options require that the params be named @Param0, @Param1, etc.
        //SQLParam is a struct (defined below) defined like the following:
        //SQLParam[] paramslist = new SQLParam[1];
        //paramslist[0] = new SQLParam(SqlDbType.VarChar, "Mike"); //or enter string variable for the second param, since the first param is SqlDbType.VarChar
        //dt = QueryResultsWithParams("SELECT * FROM TestTable WHERE FirstName = @Param0", paramslist);  //dt is datatable - see Users/ResetPassword1 for an example of how to set this up.
        public DataTable QueryResultsWithParams(string SQL, params SQLParam[] paramlist)
            //This runs a select query with a parameter list (see restrictions above), and returns a filled data table with the query results.
        {
            SetSQLConn();
            sSQL = SQL;

            SqlCommand cmd = new SqlCommand(sSQL, conn);
            for (int i = 0; i < paramlist.Length; i++)
            {
                cmd.Parameters.Add("@Param" + i, paramlist[i].Type);
                cmd.Parameters["@Param" + i].Value = paramlist[i].Value;
            }

            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            da = null;
            cmd = null;
            return dt;
        }

        public void ActionQuery(string SQL)
        //This runs an action query (INSERT, DELETE, etc.) with parameters, and returns an error if there is one, or an empty string if it's successful.
        //see above for parameter restrictions.
        {
            Error = "";
            SetSQLConn();
            sSQL = SQL;
            bool bolIsInsert = (SQL.StartsWith("INSERT"));

            SqlCommand cmd = new SqlCommand(sSQL, conn);
            cmd.CommandType = CommandType.Text;
            try
            {
                if (bolIsInsert)
                {
                    cmd.Parameters.Add("@ID", SqlDbType.Int, 4).Direction = ParameterDirection.Output;
                }
                cmd.ExecuteNonQuery();

                if (bolIsInsert)
                {
                    try
                    {
                        InsertedID = Convert.ToInt32(cmd.Parameters["@ID"].Value);
                    } catch { }
                }
            }
            catch (SqlException e)
            {
                Error = e.Message.ToString();
            }
        }

        public void ActionQueryWithParams(string SQL, params SQLParam[] paramlist)
            //This runs an action query (INSERT, DELETE, etc.) with parameters, and returns an error if there is one, or an empty string if it's successful.
            //see above for parameter restrictions.
        {
            Error = "";
            SetSQLConn();
            sSQL = SQL;
            bool bolIsInsert = (SQL.Contains("OUTPUT INSERTED."));

            SqlCommand cmd = new SqlCommand(sSQL, conn);
            for (int i = 0; i < paramlist.Length; i++)
            {
                cmd.Parameters.Add("@Param" + i, paramlist[i].Type);
                cmd.Parameters["@Param" + i].Value = paramlist[i].Value;
            }
            System.Diagnostics.Debug.WriteLine(cmd.Parameters.ToString());

            cmd.CommandType = CommandType.Text;
            try
            {
                if (bolIsInsert)
                {
                    cmd.Parameters.Add("@ID", SqlDbType.Int, 4).Direction = ParameterDirection.Output;
                    InsertedID = (int)cmd.ExecuteScalar();
                } else
                {
                    cmd.ExecuteNonQuery();
                }
            }
            catch (SqlException e)
            {
                Error = e.Message.ToString();
            }
        }

        public void Close()
        {
            conn.Close();
        }
    }

    public struct SQLParam
    {
        private SqlDbType m_Type;
        private dynamic m_Value;
        public SqlDbType Type
        {
            get { return m_Type; }
            set { m_Type = value; }
        }

        public dynamic Value
        {
            get { return m_Value; }
            set { m_Value = value; }
        }
        public SQLParam (SqlDbType ValType, dynamic val)
        {
            m_Value = val;
            m_Type = ValType;
        }
    }
}

然后我这样调用它(使用预定义的int iCustomerID作为此示例中的唯一参数):

sSQL = "SELECT CustomerID, CustomerName FROM dbo.Customers WHERE CustomerID = @Param0";
MyDB MyConn = new MyDB();
paramslist[0] = new SQLParam(SqlDbType.Int, iCustomerID);
DataTable dt = MyConn.QueryResultsWithParams(sSQL, paramslist);

if (dt == null || (dt.Rows.Count == 0))
{
    responsetext.Text = "No rows returned.";
}
else
{
    foreach (DataRow row in dt.Rows)
    {
        string sCustomerName = row["CustomerName"].ToString();
        //write code to display the value here. You can also skip the variable assignment and just write the values directly into the response.
    }
}

以上是关于从FORM传递参数到存储过程的主要内容,如果未能解决你的问题,请参考以下文章

将日期时间参数从管道传递到数据流源存储过程 Azure 数据工厂

如何将输出参数从 vb.net 传递到 mysql 存储过程?

将参数从 ReportViewer 传递到 s-s-rS 报告的存储过程数据源

将接口从片段传递到kotlin中的活动

如何从.net代码将表值参数传递给存储过程

将变量从 Access(前端)传递到 Oracle(后端)存储过程