无法在MVC中传递&符号和哈希符号

时间:2014-07-02 13:24:50

标签: ajax asp.net-mvc asp.net-mvc-4

我有这段代码

@using (Ajax.BeginForm("LoadFilter", "Contact", new { filterType = (int)FilterContactBy.Name }, new AjaxOptions { OnBegin = "ShowProgrees", OnSuccess = "HideProgress" }))
{
      @Html.TextBoxFor(m => m.ContactFilter.FilterValue, new { placeholder = "Enter a name" })                                                                                                      
      <input type="submit" class="link submit green" value="Add Filter" />                            
 }

很明显,ShowProgressHideProgress方法除了显示和隐藏加载程序gif之外什么都不做。

后端的方法是

 [HttpPost]
 public ActionResult LoadFilter(ContactListModel filter, int filterType=0, Boolean isAllFilterApply=true)
 {
     if (filter != null)
     {
         // process here
     }
 }

如果输入任何内容,它可以正常工作,例如

hi
test
me & you
contact #1
contact #1 and me

BUT
当我在任何错误发生时一起输入&#时。加载器gif只是继续移动,Controller上的代码永远不会被命中。

此外,在Chrome控制台中,它显示500 Internal Server Error(Firefox也是如此!)。

我的解决方案
我尝试了escapeenocodeURIComponent,但没有奏效。这是我尝试的方法

$.ajaxPrefilter(function(o, org, xhr) { 
  if (org.url.indexOf('/Contact/LoadFilter?filterType=') > -1) {
    // console.log(org.data[0].value);
    org.data[0].value = encodeURIComponent(org.data[0].value);
    // console.log(org.data[0].value);    
  }
});

输出(在控制台中)

&#
%26%23 

当我使用encodeURIComponent代替escape时,输出相同

&#
%26%23

但它仍然没有触及控制器上的方法。任何人都可以帮助我找到解决方案,更重要的是,告诉我为什么首先发生这种情况?

PS
请不要问我在联系人过滤器中输入&#的用法是什么,或者删除它们并告诉客户端这不是有效的输入。我不能这样做,所以请不要这么做。

更新
有人甚至读完这个吗?我不是要求我如何解码即可。请在将其标记为重复或标记为关闭之前阅读完整的问题。

2 个答案:

答案 0 :(得分:3)

好的,我知道了。

我在代码中Application_BeginRequest创建了Global.asax,就像这样..

protected void Application_BeginRequest(Object sender, EventArgs e)
        {
            var httpApp = (HttpApplication)sender;
            Debug.Write(httpApp);
        }

我坐在httpApp的断点处,然后在watch窗口中检查httpApp.Request,发现它在那里。它说(something I don't remember right now) threw an exception of type 'System.Web.HttpRequestValidationException'

所以,我得知错误是因为这个,所以在方法LoadFilter上,我刚刚添加了属性ValidateInput(false),并且它正在工作

[HttpPost]
[ValidateInput(false)]
 public ActionResult LoadFilter(ContactListModel filter, int filterType=0, Boolean isAllFilterApply=true)
 {
   // process here
 }

虽然,我必须在这里检查sql注入,因为我们正在根据收到的输入构建动态查询。

答案 1 :(得分:-3)

使用

HttpUtility.UrlDecode("url")