ajax send 2d array to action method error - asp.net mvc - javascript

i want to send 2d array from javascript file to action method.
My javascript function
function _tbdata() {
var dataarr = [];
for(var i = 0; i<svarr.length; i++)
{
var trangthai = $("input[name='" + svarr[i] + "']:checked").val();
var lydo = $("#" + svarr[i]).val();
dataarr[i] = new Array(2);
dataarr[i][0] = trangthai;
dataarr[i][1] = lydo;
}
$.ajax({
url: '/DiemDanh/testMethod',
data: { info: JSON.stringify(dataarr ) },
type: "POST",
traditional:true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('running');
},
error: function (data, textStatus) { alert(textStatus); }
});
}
And my controller
[HttpPost]
public ActionResult testMethod(List<List<string>> info)
{
return RedirectToAction("Index");
}
And when i debug in chrome, i got error
POST http://localhost:56602/DiemDanh/testMethod 500 (Internal Server
Error)
Sorry about my Enligsh is bad, Hope suggest from everybody!!!

I think you should change your javascript. Two dimensional array sholud be [[]]
I've write an example for your code. It works fine.
function Test() {
var dataarr = [[]];
for (var i = 0; i < 1; i++) {
dataarr[i][0] = "A" + i.toString();
dataarr[i][1] = "B" + i.toString();
}
var model = JSON.stringify(dataarr);
$.ajax({
url: '/Home/testMethod',
data: model,
type: "POST",
traditional: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('running');
},
error: function (data, textStatus) { alert(textStatus); }
});
}

Change your ajax like this.
$.ajax({
url: '/DiemDanh/testMethod',
data: { info: JSON.stringify(ngay) },
type: "POST",
traditional:true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('running');
},
error: function (data, textStatus) { alert(textStatus); }
});
}

change your method parameter with string multi dimensional array it will work because list of list strings parameter won't work it'll not accepting 2d array
[HttpPost]
public ActionResult testMethod(string [][] info)
{
return RedirectToAction("Index");
}

Related

How to pass string array to controller using ajax?

// something defined deleteArr and pass values to it
var postData = { deleteArr: deleteArr };
if(deleteArr.length > 0)
{
$.ajax({
url: "#Url.Action("Delete", "ASZ01")",
type: "POST",
data: postData,
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("success.");
},
error: function (response) {
alert(deleteArr[0]);
}
});
deleteArr.length = 0;
}
The above code is javascript.
Until $.ajax begin I can confirm that values in array is correct in immediate window,but when it comes to error: I got "undefined".
And the following is my function in controller
public void Delete(List<string> deleteArr)
{
service.Delete(deleteArr);
}
The second question is that I set breakpoint on that function but it can't stop.
I think maybe my ajax form is wrong?
Stringify to JSON, add the dataType: 'json' and then pass and also correct your ""
var postData = JSON.stringify({ deleteArr: deleteArr });
if(deleteArr.length > 0)
{
$.ajax({
url: #Url.Action("Delete", "ASZ01"),
type: "POST",
data: postData,
dataType: 'json'
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("success.");
},
error: function (response) {
alert(deleteArr[0]);
}
});
deleteArr.length = 0;
}
Small change to your postData
var postData = { deleteArr: JSON.stringify(deleteArr) };
Idea is to convert your array data into string format ie:JSON and posting to the server, The default Model binder of MVC framework will handle the part to convert them into List<string> for you

JavaScript POST falls when connect to MVC controller

I'm new in MVC and trying to create a site for training.
I need to call a POST method in my controller through JavaScript.
This is my JavaScript method:
function ActivateAddStarAndRoleWithCategories(sender, args) {
var discID = $('#DiscID').val();
var starID = $('#StarID').val();
var desc = $("#Description").val();
var strID = "";
$(':checkbox').each(function () {
strID += this.checked ? this.id + "," : "";
});
strID = strID.substr(0, strID.length - 1);
$.ajax({
type: "POST",
url: 'CreateCategoriesID',
contentType: "application/json; charset=utf-8",
data: {
discID: discID,
starID: starID,
description: desc,
catID: strID
},
dataType: "json",
success: function () { alert("success!"); },
error: function () { alert("Fail!"); }
});
}
And this is my method in the controller:
[HttpPost]
public ActionResult CreateCategoriesID(string discID, string starID, string description, string catID)
{
entities.AddStarAndRoleAndCategories(int.Parse(starID), description, int.Parse(discID), catID);
return Json("OK", JsonRequestBehavior.AllowGet);
}
The view that activates the JavaScript function is already connected to the controller.
I always get error 500 - the server responded with a status of 500.
What am I doing wrong?
Thank you in advance!
I would go with the examples from the jQuery docs.
Did you try something like...?
$.ajax({
method: "POST",
url: "CreateCategoriesID", // Insert your full URL here, that COULD be the problem too
// This contentType is the default, so we can just ignore it
//contentType: "application/x-www-form-urlencoded; charset=UTF-8",
// I would also ignore the dataType unless your backend explicitly sends a JSON response header
//dataType: "json",
data: {
discID: discID,
starID: starID,
description: desc,
catID: strID
}
}).done(function(msg) {
alert('Success with message: ' + msg);
}).fail(function(jqXHR, textStatus) {
alert('Failed with status: ' + textStatus);
});

How to pass a list of id's in a AJAX request to the Server in MVC

In a AJAX request to the server in MVC, how can I pass a list of id's to the controller's action function?
I accept with or without use of Html helpers.
I know MVC's model binder has no problem when it comes to simple types like int, string and bool.
Is it something like I have to use and array instead in the action?
I don't care if I have to use an array or List and even if the strings I int or strings I can always convert them. I just need them on the server.
My List ids gives null at the moment.
Javascript:
var ids= [1,4,5];
// ajax request with ids..
MVC Action:
public ActionResult ShowComputerPackageBuffer(List<int> ids) // ids are null
{
// build model ect..
return PartialView(model);
}
EDIT: Added my AJAX request
$(document).ready(function () {
$('#spanComputerPackagesBuffer').on('click', function () {
var ids = $('#divComputerPackagesBuffer').data('buffer');
console.log('bufferIds: ' + bufferIds);
var data = {
ids: ids
};
var url = getUrlShowComputerPackageBuffer();
loadTable(url, "result", data);
});
});
// AJAX's
function loadTable(url, updateTargetId, data) {
var promise = $.ajax({
url: url,
dataType: "html",
data: data
})
.done(function (result) {
$('#' + updateTargetId).html(result);
})
.fail(function (jqXhr, textStatus, errorThrown) {
var errMsg = textStatus.toUpperCase() + ": " + errorThrown + '. Could not load HTML.';
alert(errMsg);
});
};
// URL's
function getUrlShowComputerPackageBuffer() {
return '#Url.Action("ShowComputerPackageBuffer", "Buffer")';
};
SOLUTIONS: // Thanks to #aherrick comment. I missed the good old "traditional"
$.ajax({
type: "POST",
url: '#Url.Action("ShowComputerPackageBuffer", "Buffer")',
dataType: "json",
traditional: true,
data: {
bufferIds: bufferIds
}
});
Use the traditional parameter and set it to true.
$.ajax({
type: "POST",
url: "/URL",
dataType: "json",
traditional: true,
data: {}
});
Try this one (I've checked it):
$(function () {
var ids = [1, 4, 5];
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '#Url.Action("YourAction", "YourController")',
data: JSON.stringify( { ids: ids })
}).done(function () {
});
});
You have to make sure your contentType is application/json and your data is stringified.
public ActionResult SaveSomething(int[] requestData)
//or
public ActionResult SaveSomething(IEnumerable<int> requestData)
Using Action Result you cannot receive JSON object:
Using Controler:
[HttpPost]
[Route( "api/Controller/SaveSomething" )]
public object SaveTimeSheet( int[] requestData )
{
try
{
doSomethingWith( requestData );
return new
{
status = "Ok",
message = "Updated!"
};
}
catch( Exception ex )
{
return new
{
status = "Error",
message = ex.Message
};
}
}
java script:
var ids = [1,4,5];
var baseUrl: 'localhost/yourwebsite'
$.ajax({
url: baseUrl + '/api/Controller/SaveSomething',
type: 'POST',
data: JSON.stringify(ids),
dataType: 'json',
contentType: 'application/json',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
if (result != undefined) {
window.location.href = window.location.href;
}
},
async: false,
});

How to get data from Ajax

I have a variable called sid which handle number of seat. I want to throw sid to TryJSON.aspx method test. then I wanna do manipulate data on method test then throw back the result to this ajax. but I have an error when I just try to throw sid
var sid = jQuery(this).attr('id');
console.log(sid);
$.ajax({
url: "TryJSON.aspx/test",
type: "POST",
data: JSON.stringify({ 'noSeat': sid }),
contentType: "application/json; charset=utf-8",
success: function (response) {
var arr = JSON.parse(response.d);
console.log(arr);
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
});
this is my C# code to receive noSeat
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
// return noSeat;
//JavaScriptSerializer serializer = new JavaScriptSerializer();
// return new JavaScriptSerializer().Serialize(new { noSeat = noSeat });
}
I have try return only noSeat and also with Javascript serializer. but it has an error. it says
An attempt was made to call the method 'test' using a POST request, which is not allowed.
I have been tried
return "Success !!"
but it doesn't appear on console and still same error.
what's the matter ?
var sid = jQuery(this).attr('id');
console.log(sid);
$.ajax({
url: "TryJSON.aspx/test",
type: "POST",
data: JSON.stringify({ 'noSeat': sid }),
contentType: "application/json; charset=utf-8",
dataType:'json',
success: function (response) {
var arr = JSON.parse(response.d);
console.log(arr);
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
});

Server side method not getting called

From the below javascript code i am trying to call a serverside method, but serververside method is not getting called. I am using jquery, ajax
<script type="text/javascript" src="JquryLib.js"></script>
<script type="text/javascript" language="javascript">
function fnPopulateCities() {
debugger;
var State = $("#ddlState").val();
GetCities(State);
return false;
}
function GetCities(StateId) {
debugger;
var v1 = 'StateId: ' + StateId;
$.ajax(
{
type: "POST",
url: 'DropDownList_Cascade.aspx/PopulateCities',
data: '{' + v1 + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.status === "OK") {
alert('Success!!');
}
else {
fnDisplayCities(result);
}
},
error: function (req, status, error) {
alert("Sorry! Not able to retrieve cities");
}
});
}
</script>
This is my serverside method which i need to call.
private static ArrayList PopulateCities(int StateId)
{
//this code returns Cities ArrayList from database.
}
It is giving me the following error: 500 (Internal Server Error)
I cannot figure out what is wrong. please help!
Stack Trace:
[ArgumentException: Unknown web method PopulateCities.Parameter name: methodName]
use this script:
function fnPopulateCities() {
debugger;
var State = $("#ddlState").val();
GetCities(State);
return false;
}
function GetCities(StateId) {
debugger;
var data = {
'StateId': StateId
};
$.ajax({
type: "POST",
url: 'DropDownList_Cascade.aspx/PopulateCities',
data: JSON.stringify(data), // using from JSON.stringify is much better than to try stringify data manually
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.status === "OK") {
alert('Success!!');
}
else {
fnDisplayCities(result);
}
},
error: function (req, status, error) {
alert("Sorry! Not able to retrieve cities");
}
});
}
and this code for your code behind:
[System.Web.Services.WebMethod]
public static ArrayList PopulateCities(int StateId)
{
//this code returns Cities ArrayList from database.
}
Use this script
function GetCities(StateId) {
debugger;
var v1 = "{'StateId': '" + StateId+"'}";
$.ajax({
type: "POST",
url: 'DropDownList_Cascade.aspx/PopulateCities',
data: v1,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.status === "OK") {
alert('Success!!');
}
else {
fnDisplayCities(result);
}
},
error: function (req, status, error) {
alert("Sorry! Not able to retrieve cities");
}
});
}
and modify Code Behind
[System.Web.Services.WebMethod]
public static ArrayList PopulateCities(int StateId)
{
//this code returns Cities ArrayList from database.
}

Categories

Resources