如何传递字符串javascript变量以获取web.config值

How to pass string javascript variable to get web.config values

本文关键字:获取 web config 变量 何传递 字符串 javascript      更新时间:2023-09-26

我正在尝试以下代码在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];
} 

然而,javscript变量minCodemaxCode是未定义的。请告诉我是否有可能实现。

不能直接从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);
});