【问题标题】:URL parameter values are missing in action method of ASP.Net MVCASP.Net MVC 的操作方法中缺少 URL 参数值
【发布时间】:2012-11-09 07:20:25
【问题描述】:

我想将 textarea 值和其他一些参数传递给 action 方法。所以我按照以下方式使用了jquery。

查看:-

@Html.TextArea("aboutme")
<a id="@Profile.Id" title="@Profile.name" onclick="SubmitProfile(this)" >
 Submit</a>

jquery方法:-

function SubmitReview(e,count) {    
    var Text = "'"+jQuery("#aboutme").val()+"'";
    var url = 'http://' + window.location.host + '/Controller/ActionMethod?' + 'id=' + e.id       + '&name=' + e.title + '&aboutme=' + Text;
    jQuery("#Profile").load(url);

}

操作方法:-

public ActionResult ActionMethod(string id,string name,string aboutme)
        {
            //
        }

上面的代码工作正常,但是当任何一个参数值包含 空格 时。在 Jquery 方法中,URL 看起来不错。但在 action 方法中,它将值修剪到第一个空格,其余参数为空。

让我用一些例子来解释

假设 id='123',name='amith cho' ,aboutme='我是软件工程师'

Jquery 方法中的 URL

url='http://localhost/Controller/ActionMethod?id=123&name=amith cho ,aboutme=i am software engg'

但它正在作为id=123 name=amith aboutme=null 采取行动方法

如何解决?

【问题讨论】:

  • 使用此 URL http://localhost/Controller/ActionMethod?id=123&amp;name=amith cho ,aboutme=i am software engg 将数据发送到操作是 badbadbad 做法...改为发布这些值。

标签: jquery asp.net-mvc-3 url asp.net-mvc-routing


【解决方案1】:

如果您将输入值作为查询参数传递,您应该对输入值进行 url 编码。

function SubmitReview(e,count) {
    var Text = jQuery("#aboutme").val(); // quotes aren't necessary
    var url = 'http://' + window.location.host + '/Controller/ActionMethod?' 
                   + 'id=' + e.id 
                   + '&name=' + encodeURIComponent(e.title) 
                   + '&aboutme=' + encodeURIComponent(Text); 
    jQuery("#Profile").load(url);

}

如果您的字符串包含 encodeURIComponent 未处理的额外字符,您可以尝试此函数,该函数引用自 MDN docs。将上面对 encodeURIComponent 的调用替换为对 this 的调用。

function fixedEncodeURIComponent (str) {
  return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}

【讨论】:

  • encodeURIComponent() 不允许这些特殊字符 ~!*()' 所以它正在破坏......
  • @User_MVC - 更新了文档中的替代建议以包含更多转义字符。
猜你喜欢
  • 2013-06-07
  • 1970-01-01
  • 1970-01-01
  • 2022-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多