我正在尝试使用代码来获取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变量minCode
和maxCode
未定义。如果有可能,请告诉我。
答案 0 :(得分: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);
});