本文介绍了Javascript Regex强制将$ .param返回的url字符串转换为MVC模型绑定约定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下jQuery代码:

The following jQuery code:

 $.param({                                        
                  Parts: [{ hasLabel: "label", hasType: "type", hasIndex : 1 }],
                  LastKey : "LastKey",
                  Term : "Term"                             
         })

给出以下输出:

 "Parts%5B0%5D%5BhasLabel%5D=label&Parts%5B0%5D%5BhasType%5D=type&Parts%5B0%5D%5BhasIndex%5D=1&LastKey=LastKey&Term=Term"

解码为(使用decodeURI()):

which decodes to (using decodeURI()) :

 "Parts[0][hasLabel]=label&Parts[0][hasType]=type&Parts[0][hasIndex]=0&LastKey=LastKey&Term=Term"

但是,MVC中的默认模型绑定器需要以下内容:

However, the default model binder in MVC expects the following:

 "Parts[0].hasLabel=label&Parts[0].hasType=type&Parts[0].hasIndex=0&LastKey=LastKey&Term=Term"

我正在寻找一个Javascript Regex来强制编码的字符串(仍然编码)字符串,但是一个解码为正确的模型绑定约定。

I'm looking for a Javascript Regex to coerce the encoded string into a (still encoded) string , but one that decodes to the correct model binding convention.

推荐答案

以下应该做的伎俩:

var params = "Parts[0][hasLabel]=label&Parts[0][hasType]=type&Parts[0][hasIndex]=0&LastKey=LastKey&Term=Term";
var mvcParams = params.replace(/\[([^0-9]+)\]/g,'.$1');

编辑:

要工作编码字符串执行以下操作:

To work on an encoded string do the following:

var params = "Parts%5B0%5D%5BhasLabel%5D=label&Parts%5B0%5D%5BhasType%5D=type&Parts%5B0%5D%5BhasIndex%5D=1&LastKey=LastKey&Term=Term";
var mvcParams = params.replace(/%5b([^0-9]+)%5d/gi,'.$1');

这篇关于Javascript Regex强制将$ .param返回的url字符串转换为MVC模型绑定约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 20:44