2

I have actionresult as below

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

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 displays value as ["\1",\"2\"]

Normally value should display as "1","2" in string array.

Where i miss in ajax code ?

Any help will be appreciated.

Thanks.

1 Answer 1

1

SelectedFeatures is received as a single string value because you're using JSON.stringify on the actual array before sending the ajax request. When you're making a jQuery ajax request you can specify the data to be sent to the server with plain JavaScript object. 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.

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");
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Almost :). Parameter selectedFeatures will be null. You need to add the traditional: true, ajax option to make this work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.