簡體   English   中英

在 javascript 代碼中從控制器調用函數

[英]call function from Controller in javascript code

使用 d3.js 圖表,我在查看 cshtml 頁面中添加了圖表。 現在我希望圖中的值將從我的數據庫中撤回。 所以我在控制器中編寫了以下函數:

    protected int GetReadinessAvg()
    {
        var avgReadiness = 0;
        var countItems = 0;
        foreach (var item in db.Reviews)
        {
            avgReadiness = avgReadiness + item.LecturerReadine;
            countItems++;
        }
        avgReadiness = avgReadiness / countItems;

        return avgReadiness;
    }

這個函數很好用並且真的返回了相關的值。 現在,在圖表(Js 代碼)中,我想使用這個值。 這是我想要做的..

 var freqData = [
                 { State: '2013', freq: { LecturerReadine: '<%=GetReadinessAvg()%>', LecturerTransferRate: 412, LecturerAttitude: 674, LecturerKnowledge: 2001 } }
                , { State: '2014', freq: { LecturerReadine: 932, LecturerTransferRate: 2149, LecturerAttitude: 418, LecturerKnowledge: 4726 } }
                , { State: '2015', freq: { LecturerReadine: 832, LecturerTransferRate: 1152, LecturerAttitude: 1862, LecturerKnowledge: 2135 } }
                ];

但是調用函數: LecturerReadine: '<%=GetReadinessAvg()%>' 不起作用。 有什么建議?

正如@Remy Grandin 所說,您不能直接從 JavaScript 調用控制器方法。 但是您可以在 .cshtml 頁面中調用 C# 函數。 Use @functions {..}

@functions{

 protected int GetReadinessAvg()
    {
        var avgReadiness = 0;
        var countItems = 0;
        foreach (var item in db.Reviews)
        {
            avgReadiness = avgReadiness + item.LecturerReadine;
            countItems++;
        }
        avgReadiness = avgReadiness / countItems;

        return avgReadiness;
    }

}

然后賦值。

var freqData = [
                 { State: '2013', freq: { LecturerReadine: '@GetReadinessAvg()', LecturerTransferRate: 412, LecturerAttitude: 674, LecturerKnowledge: 2001 } }
                , { State: '2014', freq: { LecturerReadine: 932, LecturerTransferRate: 2149, LecturerAttitude: 418, LecturerKnowledge: 4726 } }
                , { State: '2015', freq: { LecturerReadine: 832, LecturerTransferRate: 1152, LecturerAttitude: 1862, LecturerKnowledge: 2135 } }
                ];

在 ASP MVC 中,您不能直接調用 C# 函數。 但是,您可以做的是將此函數轉換為操作並使用控制器Content()函數格式化 xml 或 json 響應。

有了這個 xml 或 json 可用,您可以進行簡單的 js AJAX 調用並將數據加載到您的圖形中。

暫無
暫無

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

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