如何访问代码隐藏中的存储过程返回的值

时间:2018-04-18 06:15:44

标签: javascript c# html sql-server

我是存储过程的初学者。我想获得2列的总和,并在HTML中以不同的标签显示它。我想知道我的代码问题的主要来源是什么。

C#调试器说'确保列中存在该列'。

存储过程:

CREATE PROCEDURE [dbo].[spTotalOverTime]
    @tsdate DATE = '2018/1/1'
AS
BEGIN
    SELECT SUM(Overtime), SUM(PlanOt)
    FROM tblTimesheet           
    WHERE YEAR(tsDate) =  YEAR(@tsDate)  AND MONTH(tsDate) = MONTH(@tsdate)
END

HTML:

<div class="row cells12">
    <div class="cell colspan4 offset1">
        <h6 class="mif-hour-glass"> Total Planned Overtime:</h6>
        <div>
            <label id="lblPlan"></label>
        </div>
        <br />
    </div>
    <div class="cell colspan4 offset1">
        <h6 class="mif-alarm"> Total Actual Overtime:</h6>
        <div>
            <label id="lblActual"></label>
        </div>
    </div>
</div>

C#

[WebMethod]
public string LoadOT(DateTime date)
{
    List<OTTotal> mylist = new List<OTTotal>();
    using (SqlConnection connection = new SqlConnection(connectionString()))
    {
        connection.Open();
        SqlCommand cmd = new SqlCommand("spTotalOverTime", connection);
        cmd.Parameters.Add("@tsdate", SqlDbType.Date).Value = date;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandTimeout = 0;

        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            mylist.Add(new OTTotal
            {
                 OTAct = Convert.ToDouble(dr["Overtime"].ToString()),
                 OTPlan = Convert.ToDouble(dr["PlanOt"].ToString())
            });
        }
        dr.Close();
        connection.Close();
    }
    JavaScriptSerializer jss = new JavaScriptSerializer();
    string jsn = jss.Serialize(mylist);
    return jsn;
}

的JavaScript

function getOTVal(year, month) {
    var asd = "{'date':'" + year + "/" + month + "/1" + "'}";
    $.ajax({
        type: 'POST',
        url: '../WebService/wsSummary.asmx/LoadOT',
        dataType: 'json',
        data: asd,
        contentType: 'application/json; charset=utf-8',
        success: function (response) {
            var cells = eval("(" + response.d + ")");
            for (var i = 0; i < cells.length; i++) {
                $('#lblActual').text(cells[i].OTAct);
                $('#lblPlan').text(cells[i].OTPlan);
            }
        },
        error: function (error) {
            alert(JSON.stringify(error))
            console.log(error);
        }
    });
}

1 个答案:

答案 0 :(得分:2)

问题是您的存储过程不会返回名为Overtime和PlanOt的列。当您在列上应用函数时,结果列是未命名的,因此您应该为它指定一个别名,如下所示:

CREATE PROCEDURE [dbo].[spTotalOverTime]
    @tsdate DATE = '2018/1/1'
AS
BEGIN
    SELECT SUM(Overtime) AS Overtime, SUM(PlanOt) AS PlanOt
    FROM tblTimesheet         
    WHERE YEAR(tsDate) = YEAR(@tsDate) AND MONTH(tsDate) = MONTH(@tsdate)
END