簡體   English   中英

如何使用Javascript和SQL計算“總計”?

[英]How to calculate “total” using Javascript and SQL?

我想計算金額的總和,並從下拉列表中選擇一個值時顯示它。 這是SQl Server中的查詢;

select Sum(Total) from tbl_CordinatorPayments where fk_repId=2

所以,這是我的下拉列表;

<select name="selectCity" id="CityDDL" class="form-control" onchange="getValue()">
                <option value="-1">--Select Rep--</option>
                @foreach (var item in ViewBag.reps)
                {
                    <option value="@item.id">@item.Name</option>
                }

            </select>

並通過使用此命令從下拉列表中獲取值的ID

function getValue() {
    var value = $("#CityDDL").val();
}

所以,我想要的是當用戶從下拉列表中選擇任何值時,它應該運行此Sql查詢;

"select Sum(Total) from tbl_CordinatorPayments where fk_repId=Id from the drop down"

采用LINQ格式或Entity Framework查詢格式,並且總計應顯示在

<p id="Total"></p>

我不知道如何從下拉列表中獲得Id的值,並在查詢的where子句中使用它。

任何幫助,將不勝感激。 謝謝!!!

在jquery中,您需要調用mvc或API控制器以獲取總值,如下所示

function getValue() {
    var value = $("#CityDDL").val();

    $.ajax({
        url: '<%: Url.Action("yourActionMethod")%>',
        data: { 'id' : value},
        type: "post",
        cache: false,
        success: function (result) {
            $('#Total').text(result);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            $('#Total').text("Error encountered while getting total");
        }
    });
}

在MVC控制器中

    [HttpPost]
    public ActionResult yourActionMethod(int id)
    {          
         var result = _db.tbl_CordinatorPayments.Where(cp => cp.fk_repId == id).Sum(cp => cp.Total);
         return result;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM