-1

MVC ビューで web.config 値を取得するために次のコードを試しています。

function GetMinMax(Code) {
    var newCode= Code;
    var minCode =newCode+"MinValue";
    var maxCode =newCode+"MaxValue";

    var minValue = @Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings[minCode]);
    var maxValue = @Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings[maxCode]);
    return [minValue, maxValue];
} 

minCodeただし、javascript 変数maxCodeは未定義です。達成可能かどうか教えてください。

4

1 に答える 1

2

javascript から web.config 値を直接取得することはできません。もしそれが可能であれば、それは巨大なセキュリティ上の脆弱性だったでしょう。考えてみてください。

そのためには、サーバーに AJAX リクエストを送信し、javascript 変数 ( code) をサーバーに渡す必要があります。サーバーは、web.config の構成値を検索し、結果をクライアントに返します。

function GetMinMax(code, callback) {
    var minValueKey = code + 'MinValue';
    var maxValueKey = code + 'MaxValue';

    $.getJSON(
        '/some_controller/some_action', 
        { 
            minValueKey: minValueKey, 
            maxValueKey: maxValueKey 
        }, 
        callback
    );
}

および対応するアクション:

public ActionResult SomeAction(string minValueKey, string maxValueKey) 
{
    int minValue = int.Parse(ConfigurationManager.AppSettings[minValueKey]);
    int maxValue = int.Parse(ConfigurationManager.AppSettings[maxValueKey]);

    var result = new[] { minValue, maxValue };
    return Json(result, JsonRequestBehavior.AllowGet);
}

クライアントで関数を使用する方法は次のとおりです。

GetMinMax('SomeCode', function(result) {
    // do something with the result here => it will be an array with 2 elements
    // the min and max values
    var minValue = result[0];
    var maxValue = result[1];

    alert('minValue: ' + minValue + ', maxValue: ' + maxValue);
});
于 2013-09-03T07:06:32.877 に答える