简体   繁体   English

Javascript发布数组显示语法错误

[英]Javascript posting array displaying syntax wrong

I have actionresult as below我的行动结果如下

[HttpPost]
public ActionResult AddRoomFeature(string[] selectedFeatures, int RoomID)
{
    return View();
}

Javascript Ajax Javascript Ajax

var selectedFeatures = [];

$('input.Hotelfeature:checkbox:checked').each(function () {
    selectedFeatures.push($(this).val());
});

$.ajax({
    type: 'POST',
    url: '@Url.Action("AddRoomFeature", "HotelRoom")',
    data: {
        selectedFeatures: JSON.stringify(selectedFeatures),
        RoomID: $("#RoomID").val()
    },
    success: function (data) {
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("error");
    }
});

Question:题:

If i post selectedFeatures to actionresult,如果我将 selectedFeatures 发布到 actionresult,

selectedFeatures displays value as ["\\1",\\"2\\"] selectedFeatures 将值显示为["\\1",\\"2\\"]

Normally value should display as "1","2" in string array.通常值应在字符串数组中显示为“1”、“2”

Where i miss in ajax code ?我在 ajax 代码中错过了什么?

Any help will be appreciated.任何帮助将不胜感激。

Thanks.谢谢。

SelectedFeatures is received as a single string value because you're using JSON.stringify on the actual array before sending the ajax request. SelectedFeatures作为单个字符串值接收,因为您在发送 ajax 请求之前在实际数组上使用JSON.stringify When you're making a jQuery ajax request you can specify the data to be sent to the server with plain JavaScript object.当您发出 jQuery ajax 请求时,您可以使用纯 JavaScript 对象指定要发送到服务器的数据。 Manual serialization is not needed.不需要手动序列化。 The data is converted to a query string or a request body.数据被转换为查询字符串或请求正文。 The default content type is application/form-url-encoded .默认的内容类型是application/form-url-encoded

So, to work your code should become:所以,为了工作,你的代码应该变成:

var selectedFeatures = [];

$('input.Hotelfeature:checkbox:checked').each(function () {
    selectedFeatures.push($(this).val());
});

$.ajax({
    type: 'POST',
    url: '@Url.Action("AddRoomFeature", "HotelRoom")',
    data: {
        selectedFeatures: selectedFeatures, // Note the missing JSON.stringify
        RoomID: $("#RoomID").val()
    },
    success: function (data) {
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("error");
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM