MVC“Get"多个Checkboxlist值具有相同的名称从querystring,检索通过javascri

MVC "Get" Multiple Checkboxlist Values with same name from querystring, retrieve via javascript

本文关键字:querystring javascri 检索 quot Get 多个 Checkboxlist MVC      更新时间:2023-09-26

表单提交后生成的URL:

http://localhost/Search/Index?selectedOrganisationId=26195&selectedOrganisationId=26244

我有一个表单,正在做一个Get请求。我有几个隐藏的字段是存储id的选定组织id。查询字符串(selectedOrganisationId)中的参数名称使用相同的名称。

我已经通过StackOverflow检查过了,所有的解决方案似乎只带回查询字符串(26244)中给定名称的最后一个值。

如何将它们全部放入数组中?这可能吗?

MVC处理它并通过Controller -> Action完美地拾取它。

首先想到的是解析来自window.location.search的查询字符串—类似于:

// a plain old javascript object (dictionary) to store the query string
var querystring = {};
// * 'window.location.search' is the query string of the current browser page
// * replace(regex, function) is a method of string that takes 
//    - a regular expression (between two forward slashes, the 'g' means global,
//      i.e. do more than just one replace) that matches `abc=123`
//    - a function that is called for each pattern match
window.location.search.replace(/([^?=&]+)(=([^&]*))?/g, function($1, $2, $3, $4) {
    // $1 to $4 are arguments that catch the groups in the regex.
    // Only $2 and $4 are of interest.
    // If we already have seen this value append (push) it on to the array
    if ($.isArray(querystring[$2]))
        querystring[$2].push($4);
    else 
        // otherwise create a new array with the found item
        querystring[$2] = [$4];
});
console.log(querystring);
console.log(querystring.selectedOrganisationId); // an array 

正则表达式借鉴于本文,但代码扩展到考虑多个同名查询字符串项。

HTML:

<form id="organizations" method="GET" action="/Search/Index">
    <input type="checkbox" name="selectedOrganisationId[]" value="1">
    <input type="checkbox" name="selectedOrganisationId[]" value="2">
    <input type="submit" value="submit" />
</form>

只要提交表单,就会得到想要的结果。如果您希望通过Ajax调用获得响应,请这样做(使用JQuery库):

<script>
    jQuery(function($){
        $("#organizations").submit(function(e){
            e.preventDefault();
            var form = $(this);
            $.ajax({
                url: form.attr("action"),
                data: form.serialize(),
                type: form.attr("method")   
            }).done(function(data){
                 //if success
                 console.log (data); 
            }).fail(function(){
                 console.log ("something is wrong!");
            })
        }); 
    });
</script>