Why I can't send parameter to action method with ajax? - c#

This code works without sending parameter:
$(function () {
$('#Fee').on('focus', function () {
$.ajax({
url: '#Url.Action("GetFee")',
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
cache: false,
data: { },
success: function (data) {
if (data.success) {
$('#Fee').val(data.message);
}
}
});
});
});
However if I want to send a parameter to the GetFee action method it doesn't work anymore:
data: { bookname : 'book1' }
And I changed my action method to accept parameter:
[HttpPost]
public ActionResult GetFee(string bookname)

You indicated:
contentType: 'application/json; charset=utf-8',
so make sure that you respect what you claimed to be sending to the server:
data: JSON.stringify({ bookname : 'book1' })
On the other hand, if you get rid of this application/json content type in your request, jQuery will use application/x-www-form-urlencoded by default and then you can simply use this:
data: { bookname : 'book1' }

Since you are specifying the datatype 'json'. So you can send only json object in request. So you need to convert data in json format.
You can do by using the JSON.stringify() method. The JSON.stringify() method converts a JavaScript value to a JSON string.
JSON.stringify(value[, replacer[, space]])
If you don't want to use JSON datatype, you don't need to convert it.
Simply use:
$(function () {
$('#Fee').on('focus', function () {
$.ajax({
url: '#Url.Action("GetFee")',
type: "POST",
cache: false,
data: {
'bookname' : 'book1'
},
success: function (data) {
if (data.success) {
$('#Fee').val(data.message);
}
}
});
});
});

As Darin Dimitrov had previously replied, you don't send your data in the format where you declare in the contentType.
In my opinion you can choose these two ways:
1.Send your parameter like a JSON string (look at Darin Dimitrov's answer) and add a [FromBody] before the input parameter, to clarify where you want to read this value.
[HttpPost]
public ActionResult GetFee([FromBody] string bookname)
2.Avoid specifying the contentType, and dataType in your ajax call, like this
$(function () {
$('#Fee').on('focus', function () {
$.ajax({
url: '#Url.Action("GetFee")',
type: "POST",
cache: false,
data: { bookname : 'book1' },
success: function (data) {
if (data.success) {
$('#Fee').val(data.message);
}
}
});
});
});

Related

How to Receive Ajax Data values from Controller in asp mvc

using the following script, I am trying to access the variables being sent using data in the ajax function but I couldn't.
<script>
$('#inline-username').click(function () {
var comments = $('#inline-username').val();
//var selectedId = $('#hdnSelectedId').val();
$.ajax({
url: '#Url.Action("UpdateOrder")', // to get the right path to controller from TableRoutes of Asp.Net MVC
dataType: "json", //to work with json format
type: "POST", //to do a post request
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false, //avoid caching results
data: { test: $(this).text() }, // here you can pass arguments to your request if you need
success: function (data) {
// data is your result from controller
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
});
here is the action in the controller
public ActionResult UpdateOrder()
{
// some code
var test = Request.Form["test"];
return Json(new { success = true, message = "Order updated successfully" }, JsonRequestBehavior.AllowGet);
}
I tried Request.Form["test"] but the value of it is null. how should I receive the objects of data?
Your ActionResult is GET And you have no input parameter for your ActionResult so either change those or see below:
<script>
$('#inline-username').click(function () {
var comments = $('#inline-username').val();
//var selectedId = $('#hdnSelectedId').val();
$.ajax({
url: /ControllerName/ActionName
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: { test: comments },
success: function (data) {
// data is your result from controller
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
});
Then within your controller:
public ActionResult UpdateOrder(string test)
{
// some code
return Json(new { success = true, message = "Order updated successfully" }, JsonRequestBehavior.AllowGet);
}
Update
Remember if you want to use POST then action you are calling has to be [HttpPost] like:
[HttpPost]
public ActionResult Example()
When there is no HTTP above your ActionResult Then Its By Default Get.
The action method should be decorated with the [HttpPost] attribute. Have you used the debugger to ensure that you're actually calling in to that method?
You can always just define a view model in C# and then accept that as a parameter to your post method - Asp.MVC will parse the post data for you as long as the names of the values are the same as your model.
Have you marked your action method with [HttpPost] attribute. ?
This post helped me a lot. I did the GET but POST raise an Internal Server Error just with [HttpPost]:
[HttpPost]
public ActionResult SaveOrder(int id, string test, string test2)
So i had to set params data with JSON.stringify and it worked. My full ajax request for POST:
$.ajax({
url: "/Home/SaveOrder",
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: JSON.stringify({ id:2, test: "test3", test2: "msj3" }),
success: function (data) {
// data is your result from controller
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});

ASP.NET MVC And Ajax Send Data

I trying send data to my controller. Controller sends all data to client correcly but from client to controller not..
My front code:
$(document).ready(function () {
$("#MessageSend").click(function () {
var serviceURL = '/User/Chat';
var model = {
Message: $("#Message").val()
}
$.ajax({
type: "POST",
url: serviceURL,
data: model,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
});
});
And my controller, I have two versions - non of those versions works.
[HttpPost]
public IActionResult Chat(ChatMessage model)
{
Console.WriteLine(model.Message);
return Json("chamara");
}
and
[HttpPost]
public IActionResult Chat(string Message)
{
Console.WriteLine(Message);
return Json("chamara");
}
Thank you for help.
The JSON.stringify() method converts a JavaScript value to a JSON string, hence
You need to change the data in a way that the Json can "understand" it
for that change to
data: JSON.stringify(model)
for more information about it look Here
Looking at your code, seems you are trying to send a JSON to User controller but your controller is expecting a string (controller example 2).
Also, it is a good practice to create specific classes for binding events via jquery such as "js-messageSend". It will minimize the chance of your script breaking if you need to change the Message class for any reason in the future, but forget that you have an event on it.
Try this:
$(document).ready(function () {
$("#MessageSend").click(function () {
var messageText = $("#Message").val();
$.ajax({
type: "POST",
url: '/User/Chat',
data: { Message: messageText },
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
});
});

How to POST via $.ajax() to ASP.NET WEB API?

I keep getting a null parameter once the WEB API method is hit. What am I doing wrong?
var product = {
name: "productA",
Id: 22
};
$.ajax({
url: 'http://localhost:50175/api/values/',
type: 'POST',
data: product
})
.success(function(data) {
alert('success');
})
WEB API
// POST api/values
[HttpPost]
public void Post([FromBody]Product value)
{
setResponse();
}
Product class
public class Product
{
public string name { get; set; }
public int Id { get; set; }
}
You need to append Post to the url:
var product = {
name: "productA",
Id: 22
};
$.ajax({
url: 'http://localhost:50175/api/values/Post',
type: 'POST',
data: product
})
.success(function (data) {
alert('success');
})
Screen shot
Assuming you meant to post JSON to your WebAPI.
You must specify the encoding and encode it yourself. By default jQuery will form url encode the data parameter.
$.ajax({
url: 'http://localhost:50175/api/values/',
type: 'POST',
data: JSON.stringify(product),
contentType: "application/json"
})
.success(function(data) {
alert('success');
});
Try this
var product = {
name: "productA",
Id: 22
};
$.ajax({
url: 'http://localhost:50175/api/values/',
type: 'POST',
data: JSON.stringify(product),
dataType: "json"
})
.success(function(data) {
alert('success');
});
try this:
function YourMethodName() {
$.ajax({
url: '~/api/values/',
type: 'POST',
data: JSON.stringify({
product : {
name: $('#IdOfInputName"').val(),
ID: $('#idofInputID').val()
},
}),
contentType: 'application/json; charset=utf-8',
success: function (result) {
// your code
},
error: function (result) {
//your code
}
});
};
Cobbling together pieces of everyone's answers, I found the solution.
Remove [FromBody] in the Web API parameter. #Big Daddy mentioned this in an OP comment but then said to use HttpRequestMessage, which is not available.
Using code from the OP, the above is the only modification.
Some additional comments, at least for my scenario:
Don't use JSON.stringify(), which I was not in the OP.
contentType: 'application/json; charset=utf-8' will cause values to be null
type didn't matter
Don't append Post to the endpoint URL
I'm not sure why [FromBody] is there in the first place. I guess Microsoft is assuming everyone will be POSTing FORMs? That's unrealistic.

Property's value (datetime) change from ajax call to mvc 4 controller method

I am passing a viewModel from ajax call like this:
$.ajax("url", {
data: JSON.stringify({ vm: ko.toJS(ko.utils.unwrapObservable(window.viewModel)) }),
type: "POST",
async: performAsyncCall !== undefined ? performAsyncCall : true,
contentType: "application/json",
dataType: "json",
success: function (result) {
//Code here
},
error: function (error) {
//Code here
},
complete: function () {
//Code here
}
});
And my controller method (using mvc 4) is like this:
[HttpPost]
public ActionResult Method(CustomViewModel vm)
{
//Code here
}
window.viewModel (on javascript code) has a property called CreationDate equal to CustomViewModel (on c# code) who has a CreationDate property also. Before to do the post to the server from client, CreationDate has this value (6:48am):
But the same property has this value (2:48am) on server:
I need the value that is on client but i didn't found how it value is changing, somebody can help me?
Send TimeZone offset as well and you'll know what the user time offset is. Use getTimezoneOffset() on JavaScript Date object. Documentation
If you don't want to change your model you can simply add additional parameter to your action method:
[HttpPost]
public ActionResult Method(CustomViewModel vm, int timezoneOffset)
{
//Code here
}
In JS:
var toSend = ko.toJS(ko.utils.unwrapObservable(window.viewModel));
$.ajax("url", {
data: JSON.stringify({ vm: toSend, timezoneOffset: toSend.CreationDate.getTimezoneOffset() / 60 }),
type: "POST",
async: performAsyncCall !== undefined ? performAsyncCall : true,
contentType: "application/json",
dataType: "json",
success: function (result) {
//Code here
},
error: function (error) {
//Code here
},
complete: function () {
//Code here
}
});

MVC4 cannot map object properties to JSON from AJAX POST

Model:
public class JsonRequest
{
public string Data { get; set; }
}
Action:
[HttpPost]
public ActionResult Index(JsonRequest data)
{
return new JsonResult()
{
Data = string.Format("Data: {0}", data.Data), // data.Data == null here
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
AJAX:
$.ajax({
type: 'POST',
url: '#Url.Action("Index", "Home")',
cache: false,
data: JSON.stringify({ data: "Hello World!" }),
success: function(data) {
alert(data);
}
});
JsonRequest object has an instance in Index action but it's Data property was not mapped to the passed JSON. How can I achieve this?
You need to remove JSON.stringify() call, because jQuery do it itself. And according standarts it's better to write {"Data" : "Hello world"} ("Data" in quotes).
Well you are specifying data not Data when passing the object back up to the server. This may be the root of the problem. Also specify the contentType in your AJAX request.
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '#Url.Action("Index", "Home")',
cache: false,
data: JSON.stringify({ Data: "Hello World!" }),
success: function(data) {
alert(data);
}
});
http://api.jquery.com/jQuery.ajax/

Categories

Resources