利用jquery解决MVC下A potentially dangerous Request.QueryString value was detected from the client问题

其实A potentially dangerous Request.QueryString value was detected from the client错误原因是mvc检测了您的请求,如果有‘<’等字符串,就会有这个错误。解决办法在action前加

[AcceptVerbs(HttpVerbs.Post),ValidateInput(false)]
public ActionResult New(string xmlContent) {
但是如果你在action中
return View();

还是会出现这个错误,除非

 return RedirectToAction("Result");
转到另一个action

解决方法1:

1.利用javascript的decodeURI和encodeURI方法编码字符串。

例如:
您要提交的field名字是xmlContent
那么填写如下代码
1.<% using (Html.BeginForm("New", "XML", FormMethod.Get, new { @onsubmit = "return CheckForm();" }))

2.form提交时进行编码

 function CheckForm() {
result = jQuery.formValidator.pageIsValid();
if (jQuery.formValidator.pageIsValid()) {
$("#xmlContent").val(encodeURI($("#xmlContent").val()));
}
return result;
}
3.load时进行解码
 $(document).ready(function() {
$("#xmlContent").val(decodeURI($("#xmlContent").val()));
$.formValidator.initConfig();
$("#xmlContent").formValidator({ onshow: "please input XML", onfocus: "XML required", oncorrect: "OK" })
.inputValidator({ min: 20, empty: { leftempty: false, rightempty: false, onerror: "XML length at least 20"} });
});

解决方法2:利用ajax进行表单验证,保证提交的一定正确

1.添加验证

  $(document).ready(function() {
// $("#xmlContent").val(decodeURI($("#xmlContent").val())); $.formValidator.initConfig(); $("#xmlContent").formValidator({ onshow: "please input XML", onfocus: "XML required",
oncorrect: "OK" })
.inputValidator({ min: 20, empty:
{ leftempty: false, rightempty: false, onerror: "XML length at least 20"} })
.ajaxValidator({
type: "get",
url: "checkXML",
datatype: "json",
success: function(responseText) {
if (responseText == "1") {
return true;
}
else {
return false;
}
},
buttons: $("#button"),
error: function() { alert("server busy,try later..."); },
onerror: "XML Format error",
onwait: "XML checking,please wait..." });; });
    用了猫冬大侠写的formValidator.js

2.添加action

        [AcceptVerbs(HttpVerbs.Get), ValidateInput(false)]
public ActionResult checkXML(string xmlContent)
{
bool bResult = true;
int nResult=0;
if (!string.IsNullOrEmpty(xmlContent))
{
//利用XmlSchemaSet(XSD)检查XML XmlSchemaSet validator = new XmlSchemaSet();
validator.Add("", XmlReader.Create(Server.MapPath(Url.Content("~/Models/xmlTest.xsd")))); //Url.Content必须,否则找不到文件 XDocument doc = null;
try { doc = XDocument.Parse(xmlContent); doc.Validate(validator, (sender, e) => { nResult = 0; bResult = false;
});
if (bResult)
nResult = 1;
}
catch { nResult = 0; } } return this.Json(nResult);
}

3.两者结合,较完美解决

以上两种方法结合,进行完美解决这个问题

  image

  image

代码演示和下载 我的个人网站(白天开机)MVCmembership,另外找在无锡的.net工作

      
posted @ 2009-05-11 10:31  柯南  阅读(3069)  评论(10编辑  收藏  举报