简体   繁体   English

将参数从FORM传递到存储过程

[英]Passing parameters to stored procedure from FORM

I am a SysAdmin that some how made his way to a development position. 我是SysAdmin,他是如何成为一名开发职位的。 But I am having a situation and the solution could be really simple but I been researching for the past 3 days and no luck. 但是我遇到了一个情况,解决方案可能真的很简单,但是过去三天我一直在研究,没有运气。

Here's my problem: I have built a stored procedure that returns a report with the dates and total time the students spent at the gym, I need to pass 4 parameters: 这是我的问题:我建立了一个存储过程,该过程返回一个报告,其中包含学生在体育馆里度过的日期和总时间,我需要传递4个参数:

Student ID, StartDate, EndDate, Location

I have built my form. 我已经建立了表格。

<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>

it looks like this 看起来像这样

在此处输入图片说明

This is my HomeController with my post method: 这是我的HomeController和我的post方法:

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");
    }
}

As you can see, I am capturing my post data: 如您所见,我正在捕获我的帖子数据:

在此处输入图片说明

And this is my model class: 这是我的模型课:

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

Now this is my data access layer where I need to pass those parameters: 现在这是我的数据访问层,我需要在其中传递这些参数:

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;
    }
}

As you guys can see, I'm hard coding the values now 你们可以看到,我现在正在对值进行硬编码

.Value = "02/28/2018" 

but it should be Value = Client for example. 但应为“ Value = Client”。

I try 我尝试

reportmodel obj = new reportmodel();

and add .Value = obj.Client but this is passing Null values. 并添加.Value = obj.Client但这将传递Null值。

And this is my report Controller its actually named GeneralController : 这是我的报表控制器,其实际名称为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();
}

I should be getting this 我应该得到这个

在此处输入图片说明

I know the answer is in front of me but I don't see it! 我知道答案就在我眼前,但我看不到!

I'm not sure what the issue is (you say you're not getting the desired result, but what are you getting instead?), but in case this helps, I thought I'd share the class I use for all of my database queries: 我不确定是什么问题(您说您没有得到想要的结果,但是您得到的是什么?),但是如果这有帮助,我想我会分享所有我使用的类数据库查询:

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;
        }
    }
}

Then I call it like this (using a predefined int iCustomerID as the only parameter in this example): 然后,我这样称呼它(在此示例中使用预定义的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.
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM