Pass string from jQuery to C# MVC - c#

I have problem with passing string value from jQuery to C# in Web MVC.
There is my jQuery code:
$.ajax({
type: 'POST',
url: '/Account/ChangePhoneNumber',
contentType: "application/json; charset=utf-8",
data: newPhone,
dataType: 'json',
success: function (result) {
alert("We returned: " + result);
}
})
Here is my C# method:
[HttpPost]
public ActionResult ChangePhoneNumber(string data)
{
return View();
}
While debugging data parameter is always null.
What I am doing wrong?

Ok I`ve figured out what was wrong:
$.ajax({
type: 'POST',
url: '/Account/ChangePhoneNumber',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({data: newPhone}),
dataType: 'json',
success: function (result) {
alert("We returned: " + result);
}
})
I had to add data: JSON.stringify({data: newPhone}),

You were almost there;
$.ajax({
type: 'POST',
url: '/Account/ChangePhoneNumber',
contentType: "application/json; charset=utf-8",
data: {data: newPhone, foo: bar, fooz: barz}, //<-- mind the array here
dataType: 'json',
success: function (result) {
alert("We returned: " + result);
}
})
Which will result the following;
[HttpPost]
public ActionResult ChangePhoneNumber(string data, string foo, string fooz)
{
//data will contain newPhone
//foo will contain bar
//fooz will contain barz
return View();
}
Just make sure to put the object in an array. So, in your case:
data: {data: newPhone},
will solve your problem.

You are not passing data correctly in ajax call. You need to pass it like this data: {data: newPhone},
$.ajax({
type: 'POST',
url: '/Account/ChangePhoneNumber',
contentType: "application/json; charset=utf-8",
data: {data: newPhone},
dataType: 'json',
success: function (result) {
alert("We returned: " + result);
}
})
[HttpPost]
public ActionResult ChangePhoneNumber(string data)
{
return View();
}

you need post your data as form object; some useful information can found here
$.ajax({
type: 'POST',
url: '/Account/ChangePhoneNumber',
contentType: "application/json; charset=utf-8",
data: {data: newPhone},
dataType: 'json',
success: function (result) {
alert("We returned: " + result);
}
})

Check how you defined the route.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{data}",
defaults: new { controller = "yourcontroller", action = "actionname", data = UrlParameter.Optional }
);
Please check if the parameter name in your route is "data"

If you are not worried about AJAX/JSON, you can simply use $.Post method.
var url = "#Url.Action("ChangePhoneNumber", "Account")";
$.post(url, { data: newPhone })
.fail(function() {
// do something
})
.done(function(result) {
alert("We returned: " + result);
});

Related

Send array of numbers from JS to asp.net MVC action

I want to send array of numbers to my back action and I am getting NULL or error whatever I try. This is my current code.
JS
$.ajax({
traditional: true,
dataType: "json",
contentType: 'application/json; charset=utf-8',
type: "POST",
data: JSON.stringify(groupIds),
url: '/Admin/ReadMessages',
error: function (error) {
swal.fire({
title: "Something went wrong. Please try again later.",
type: "error"
});
}
});
MVC
public ActionResult ReadMessages(List<long> groupIds)
{
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
Any ideas?
try this
var arr= new Array();
arr.push(1);
arr.push(2);
$.ajax({
type: "POST",
url: urlToPost,
data: JSON.stringify(arr),
contentType: "application/json"
});
Just to clear out for others, as #Amin stated and I realized, error was in sending NON array object, I was using map function and it returned some jquery array, but when I instantiated new Array and sent it, it worked perfectly.
$.ajax({
traditional: true,
dataType: "json",
contentType: 'application/json; charset=utf-8',
type: "POST",
data: { 'groupIds': groupIds} ,
url: '/Admin/ReadMessages',
error: function (error) {
swal.fire({
title: "Something went wrong. Please try again later.",
type: "error"
});
}
});
And in Controller :
public ActionResult ReadMessages(IEnumerable<long> groupIds))
{
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
$.ajax({
traditional: true,
dataType: "json",
contentType: 'application/json; charset=utf-8',
type: "POST",
data:{groupIds:groupIds},
url:'#Url.Action("ReadMessages", "Admin")',
error: function (error) {
swal.fire({
title: "Something went wrong. Please try again later.",
type: "error"
});
}
});
controller:
[HttpPost]
public ActionResult ReadMessages(IEnumerable<long> groupIds))
{
return new HttpStatusCodeResult(HttpStatusCode.OK);
}

send List into mvc controller with ajax

I have a List which look like the following
I want to send this list into my controller,
I am using ajax call to send data from client side to server side
here is my ajax call
$.ajax({
url: '/Main/updateTripundHoliday',
data: d.weekendLeave,
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
}
});
and my method in controller
public bool updateHoliday(List<Holidaysclass> data)
{
for (var i = 0; i < data.Count(); i++)
{
insertHolidays(data.ElementAt(i).Date, data.ElementAt(i).Day, data.ElementAt(i).HolidayName, data.ElementAt(i).isActive, data.ElementAt(i).currentYear, data.ElementAt(i).isHolidayWeekend, data.ElementAt(i).OfficialID);
}
return true;
}
here my List<Holidaysclass> data is showing null
what can I do here?
To send data from browser to controller you need to use POST type and then pass data inside ajax call. you can directly map your entites in action method.
$.ajax({
url: '/Main/updateTripundHoliday',
data: d.weekendLeave,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
}
});
and in controller put HttpPost Data Annotation
[HttpPost]
public bool updateHoliday(List<Holidaysclass> data)
{
for (var i = 0; i < data.Count(); i++)
{
insertHolidays(data.ElementAt(i).Date, data.ElementAt(i).Day, data.ElementAt(i).HolidayName, data.ElementAt(i).isActive, data.ElementAt(i).currentYear, data.ElementAt(i).isHolidayWeekend, data.ElementAt(i).OfficialID);
}
return true;
}
Using ajax get method we cant send data from client to server is not best way. try using POST method send data from client to server.
Reference : https://api.jquery.com/jquery.post/
$.ajax({
url: '/Main/updateTripundHoliday',
data: d.weekendLeave,
type: "POST",
......
});
You can do it like this :
$(document).ready(function () {
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
things = JSON.stringify({ 'things': things });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Home/PassThings',
data: things,
success: function () {
$('#result').html('"PassThings()" successfully called.');
},
failure: function (response) {
$('#result').html(response);
}
});
});
Please follow this link for more information :
link
You can not post data in get request. Instead you need to use POST type request.
Here is your updated request.
$.ajax({
url: '/Main/updateTripundHoliday',
data: d.weekendLeave,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
}
});
Also your action should have [HttpPost] annotation.
try this:
$.ajax({
url: '/Main/updateHoliday',
data: {list: d.weekendLeave},
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
}
});
[HttpPost]
public bool updateHoliday(List<Holidaysclass> list)

Error with my Ajax post with jQuery

I am trying to post to a method using jQuery and Ajax. My Ajax code is as follows:
var isMale = $(e.currentTarget).index() == 0 ? true : false;
$.ajax({
type: "POST",
url: "Default.aspx/SetUpSession",
data: { isMale: isMale },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() {
// Go to next question
}
});
And here is my WebMethod:
[WebMethod]
public static void SetUpSession(bool isMale)
{
// Do stuff
}
I get a 500 (Internal Server Error) looking at the console, the method never get's hit. After I changed data to "{}" and removed the bool from the method signature the method then gets hit, so I'm assuming its something to do with the Ajax.data attribute I'm trying to pass.
Two things you need to modify :-
1) Make sure that this line is written in your web service page and should be uncommented.
[System.Web.Script.Services.ScriptService]
2) Modify the "data" in the code as :-
$.ajax({
type: "POST",
url: "Default.aspx/SetUpSession",
data: '{ isMale:"' + isMale + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() {
// Go to next question
}
});
Pass string instead of bool
[WebMethod]
public static void SetUpSession(string isMale)
{
// Do stuff
}
Alternative you can use pagemethods through script manager.
Try following code:
var params = '{"isMale":"' + $(e.currentTarget).index() == 0 ? true : false + '"}';
$.ajax({
type: "POST",
url: "Default.aspx/SetUpSession",
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
responseType: "json",
success: function (data) {}
});
[WebMethod]
public static void SetUpSession(string isMale)
{
// Do stuff
}

List of GUIDs JSON being sent to MVC controller via GET is empty upon arrival, POST works

I am sending a collection of GUID-like objects to my MVC controller like so:
$.ajax({
type: 'GET',
url: 'http://localhost:61975/Song/GetByIds',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: {
songIds: JSON.stringify(songIds)
},
success: function (data) {
},
error: function(error) {
console.error(error);
}
});
The data being sent in my request header looks like:
songIds:["6cb44f55-9fd5-4540-9b11-75ccce816d67"]
and my MVC3 controller method looks like:
[HttpGet]
public ActionResult GetByIds(List<Guid> songIds)
{
SongManager songManager = new SongManager(SongDao, PlaylistDao, PlaylistItemDao);
IList<Song> songs = songManager.GetByIds(songIds);
return new JsonDataContractActionResult(songs);
}
In this implementation I receive a non-null List object, but it is always empty. What's my mistake?
EDIT: If I POST like this instead of GET it works fine. How come??
$.ajax({
type: 'POST',
url: 'http://localhost:61975/Song/GetByIds',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
songIds: songIds
}),
success: function (data) {
loadedSongs = loadedSongs;
if (callback) {
callback(data);
}
},
error: function(error) {
console.error(error);
}
});
You should try to use "traditional" option set to true for your jQuery Ajax request.
Refer to documentation for more details : http://api.jquery.com/jQuery.ajax/
And you should also remove the JSON.Stringify part.
Can you try this out and let me know if it worked out for you ?
I Did a test on my end and it works just fine.
$.ajax({
type: 'GET',
url: 'http://localhost:61975/Song/GetByIds',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
traditional: true, //// traditional option to true
data: {
songIds: songIds /// no JSON.stringify
},
success: function (data) {
},
error: function(error) {
console.error(error);
}
});

Ajax call not working

I am making an ajax call to C# function but it is not being call.
This is ajax call:
$('#button1 button').click(function () {
var username = "username_declared";
var firstname = "firstname_declared";
$.ajax({
type: "GET",
url: "practiced_final.aspx/ServerSideMethod",
data:{username1:username,firstname1:firstname},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$('#myDiv').text(msg.d);
},
error: function (a, b, c) {
alert(a + b + c);
}
});
return false;
});
This is C# code:
[WebMethod]
public static string ServerSideMethod(string username1, string firstname1)
{
return "Message from server with parameter." + username1 + "hello" + firstname1;
}
This method is not getting hit and shows a error message like this:
object XMLHttpRequest]parsererrorundefined
Any help will be highly appreciated.
$('#button1 button').live('click', function () {
var username = "username_declared";
var firstname = "firstname_declared";
$.ajax({
url: "/practiced_final.aspx/ServerSideMethod", type: "GET", dataType: "json",
data: JSON.stringify({ username1: username, firstname1: firstname }),
contentType: "application/json; charset=utf-8",
success: function (msg) {
$('#myDiv').text(msg.d);
},
error: function (a, b, c) {
alert(a + b + c);
}
});
});
$('button#button1') or $('#button1') or $('#button1 button')
check u selector also. put one alert message inside click event and see
Finally it is working.This is the final code.
Thanks everyone for your wise replies.
$.ajax({
type: "POST",
url: "practiced_final.aspx/hello_print",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
$('#myDiv').text(msg.d);
}
})
return false;
Enjoy.
In your code I can see : dataType: "json",
But you're not sending a Json through your C# function... When you're telling ajax that the dataType is a json, it will JSON.parse() the response. Maybe that's where the failure is.
Try changing the dataType, or removing it (jQuery will try to guess it).
Please Change below line in Jquery function.
data:{username1:username,firstname1:firstname},
to
data:"{'username1':'" + username + "','firstname1':'" + firstname + "'}",
Hope this will help you.
$('button#button1') //Or check selector put one alert inside onclick
$('#button1').live('click', function () {
var username = "username_declared";
var firstname = "firstname_declared";
$.ajax({
type: "GET",
url: "practiced_final.aspx/ServerSideMethod",
data: JSON.stringify({ username1: username, firstname1: firstname }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$('#myDiv').text(msg.d);
},
error: function (a, b, c) {
alert(a + b + c);
}
})
return false;
it may help
Try changing this line:
data:{username1:username,firstname1:firstname},
to
data:JSON.stringify({username1:username,firstname1:firstname}),
Edit:
I'm not sure if this is the cause of the problem, but this is one thing I noticed different between our jQuery ajax calls. Also, changed result string to reflect #dana's criticism in the comments of my answer.

Categories

Resources