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

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.

Related

Passing json to mvc controller

I am trying to post some data via jQuery ajax to an Asp.Net MVC controller. I have the follow class which I am working with:
public class InnerStyle
{
[JsonProperty("color")]
public string HeaderColor { get; set; }
[JsonProperty("font-size")]
public string HeaderFontSize { get; set; }
[JsonProperty("font-family")]
public string HeaderFontFamily { get; set; }
}
The post method looks like:
public JsonResult UpdateRecord(InnerStyle innerStyle)
{
//Do some validation
return Json("OK");
}
And my jQuery looks like:
$('#font-size-ddl').change(function () {
var value = $(this).val();
headerObj["font-size"] = value;
console.log(JSON.stringify({ innerStyle: headerObj }));
$.ajax({
type: "POST",
url: "#Url.Action("UpdateRecord", "Document")",
data: JSON.stringify({ innerStyle: headerObj}),
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
}
});
});
The console.log in the above change event produces the following JSON string:
{"innerStyle":{"text-align":"","font-size":"20px","color":""}}
Now the issue I am having is if I set a break point on my UpdateRecord Action and see what is coming through the innerStyle object is null. Can someone tell me where I am going wrong please.
I tried using the below code and it's working fine.
$.ajax({
type: "POST",
url: "#Url.Action("UpdateRecord", "Document")",
data: JSON.stringify({"text-align":"","font-size":"20px","color":""}),
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
}
});
I simply removed the parameter name "innerStyle". I just noticed one thing which might be a typo error. You are passing a property "text-align":"" instead of "font-family". So it's not populating all properties inside the controller's action UpdateRecord(InnerStyle innerStyle). You should pass similar to the below json object to map the entire object on controller's action UpdateRecord(InnerStyle innerStyle)
{
"color": "sample string 1",
"font-size": "sample string 2",
"font-family": "sample string 3"
}
#Code, your code is fine. It's just you cannot use [Json Property] while you are hitting controller via ajax. you have to use real class properties.
$('#font-size-ddl').change(function () {
var value = $(this).val();
var headerObj = {};
headerObj["HeaderColor"] = "Red";
headerObj["HeaderFontSize"] = value;
headerObj["HeaderFontFamily"] = "Arial";
console.log(JSON.stringify({ custom: headerObj }));
$.ajax({
type: "POST",
url: "#Url.Action("UpdateRecord", "Employee")",
traditional: true,
data: JSON.stringify({ custom: headerObj }),
dataType: JSON,
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
}
});
});

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

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);
}
}
});
});
});

data posted with jquery post to Asp.net 4 Mvc 2 as null

I am using jquery 1.8 to post data to ASP.Net 4 MVC 2 like this
PostData('Home/Login',{ "username": $("#username").val(),"password": $("#password").val()})
function PostData(url, data) {
$.ajax({
url: url,
data:data,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
Success:successFunction, Error: ErrorFunction
});
};
My model
namespace FmsMvc.Models
{
public class UsersModel
{
public int UserID { get; set; }
public string Role { get; set; }
public string Email { get; set; }
public DateTime ts { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
}
My Controller
[HttpPost]
public JsonResult Login(UsersModel u)
{
if (doSomething(Prop1, Prop2)
return Json(null); // Success
return Json(new { Status:'success',Msg:" Your username"+u.username });
}
My controller does not get the data. It gets null when debugging.
what am i doing wrong?
NOTE
I deleted all the javascript in the Scripts folder, as I am using a custom script
Have you tried JSON.strinfigy-ing your data before POSTing?
function PostData(url, data) {
$.ajax({
url: url,
data:JSON.stringify(data),
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
Success:successFunction, Error: ErrorFunction
});
};
Try it like this:
var data = { "username": $("#username").val(),
"password": $("#password").val()
};
PostData('Home/Login',JSON.stringify(data));
You can use the JQuery .post() method which will parse the values for you
var url = '#Url.Action("Login", "Home")'; // beter to use this rather than hardcoding
var userName = `$("#username").val();
var password = $("#password").val();
$.post(url, { Username: userName, Password: password }, function(result) {
// do something with the result you returned from the action method
alert(result.Msg);
});
Note, only properties Username and Password will be set in the model. The other properties will be their default values.
After much debugging, i found the culprit
in my ajax function above i have this two line
contentType: 'application/json; charset=utf-8',
dataType:'json',
Somehow, this should not be. when i submitted the form with the two lines present, this is what i saw in chrome dev
But when i removed the line contentType: 'application/json; charset=utf-8', so that the $.ajax is now
$.ajax({ // create an AJAX call...
type: 'post', // GET or POST
url: url, // the file to call
dataType:'json',
data: data, // get the form data
Success:successFunction, Error: ErrorFunction
});
when i look in chrome dev after submit, i see this, which was not there before
I dont' know why this is the case, i will try in other browsers to see if it all works

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/

ajax post data null in mvc3 controller method

One of my jquery ajax posts sends post data to my .NET MVC3 controller method, but at the controller method, the data shows up as null. I have many other ajax posts that use practically the same method body, and they all work fine, so I'm not sure what is happening.
Ajax post:
$.ajax({
url: '/Entity/Relate',
type: 'POST',
dataType: 'json',
contentType: 'applicaiton/json; charset=utf-8',
data: { primaryEntityId: parseInt(entityParentId, 10), relatedEntityId: _createdId },
success: function (data)
{
//do stuff
},
error: function ()
{
// throw error
},
complete: function ()
{
//do more stuff
}
});
Controller method:
[HttpPost]
public int Relate(int primaryEntityId, int relatedEntityId)
{
return relationshipRepository.Add(primaryEntityId, relatedEntityId);
}
The problem is when I break on the Relate method, primaryEntityId and relatedEntityId are null, even though in the post data in Firebug, it shows that {primaryEntityId: 13, relatedEntityId: 486} have been posted to the method.
Any suggestions or ideas as to why the post looks good, but the controller isn't picking up the data?
but at the controller method, the data shows up as null
That's not possible because Int32 is a value type and value types in .NET cannot be null. You probably meant that they are assigned to the default value. Anyway.
The problem is related to the contentType parameter that you have set in your AJAX request. You need to remove it because you are not sending JSON but a standard application/x-www-form-urlencoded request:
$.ajax({
url: '/Entity/Relate',
type: 'POST',
dataType: 'json',
data: {
primaryEntityId: parseInt(entityParentId, 10),
relatedEntityId: _createdId
},
success: function (data)
{
//do stuff
},
error: function ()
{
// throw error
},
complete: function ()
{
//do more stuff
}
});
If you want to send a JSON request define a view model:
public class RelateViewModel
{
public int PrimaryEntityId { get; set; }
public int RelatedEntityId { get; set; }
}
then have your controller take this view model as argument:
[HttpPost]
public int Relate(RelateViewModel model)
{
return relationshipRepository.Add(model.PrimaryEntityId, model.RelatedEntityId);
}
and finally send a real JSON request (using the JSON.stringify method):
$.ajax({
url: '/Entity/Relate',
type: 'POST',
dataType: 'json',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({
primaryEntityId: parseInt(entityParentId, 10),
relatedEntityId: _createdId
}),
success: function (data)
{
//do stuff
},
error: function ()
{
// throw error
},
complete: function ()
{
//do more stuff
}
});

Categories

Resources