Receive json object through ajax post request - c#

UNABLE TO DETECT PROBLEM
I am trying to get data from server using ajax post request but when ajax request hits back end c# method its data part gets null
here is my js code
let da = '{"sidx":'+sid+',"idx":'+cur+'}';
da = JSON.parse(da);
$.ajax({
type: "POST",
url: "../RegSaleman/next",
data: {x:da},
datatype: "Json",
complete: function (dataret) {
}
});
and c# code is
[HttpPost]
public JsonResult next(JsonResult x)
{
}

You're trying to read JsonResult, which is wrong. This class used for response from server.
You can create some data model (simple class) that will be mapped automatically by MVC framework.
Let's assume that you have JSON object:
{
"id": "someValue",
"foo" : 3,
"bar" : "bar string"
}
and you can create a class
public class MyClass
{
public string Id {get;set;}
public int Foo {get;set;}
public string Bar {get;set;}
}
As you can see, it even can map variables in different case (like Foo and "foo"), but this behavior could be altered in case of need.
And your method will be:
[HttpPost]
public JsonResult next(MyClass x)
{
}

var obj = new Object();
$.ajax({
type: "POST",
url: "/RegSaleman/next",
data: JSON.stringify(o),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
failure: function (response) {
},
error: function (response) {
}
});

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

pass value to controller by using ajax

I want to pass value from view to controller by using ajax.
<button onclick="addCommentByAjax()" >Save</button>
My script:
function addCommentByAjax() {
$.ajax({
type: "POST",
url: '/Survey/DoDetailSurvey',
data: {
choiceId: "1"
}
});
}
Controller:
[HttpPost]
public ActionResult DoDetailSurvey(SurveyViewModel model, string choiceId)
{
//
}
but choiceId always null
Change couple of things.
First assign an id or class to your button.Second remove inline onclick function and use ajax click function.Then specify the request type as Post.
$('#btnComment').click(function () {
var choiceId = $('#YourChoiceId').val();
$.ajax({
url: '/Survey/DoDetailSurvey',
data: { 'choiceId' : choiceId},
type: "post",
cache: false,
success: function (response) {
//do something with response
},
error: function (xhr, ajaxOptions, thrownError) {
alert('error occured');
}
});
});
Then your controller should look like this
[HttpPost]
public ActionResult DoDetailSurvey(string choiceId)
{
//
}
I don't know how you are populating your viewmodel,so I purposely removed them and shown an working example.
In case you want to pass viewmodel you should construct your data object like this:
var data = {};
data.Property1 = some val;
data.Property2 = "some val";
$.post('/Survey/DoDetailSurvey', data);
Sample structure of SurveyViewModel I assume:
public class SurveyViewModel
{
public int Property1 { get; set; }
public string Property2 { get; set; }
}
Since there are two parameter in your controller, you need to identify them both form the client side. Further, you should specify the contentType.
You spread the payload like so:
function addCommentByAjax() {
var payload = {
model: {
// whatever properties you might have
},
choiceId: 1
};
$.ajax({
type: "POST",
url: '/Survey/DoDetailSurvey',
contentType: 'application/json',
data: JSON.stringify(payLoad)
});
}
function addCommentByAjax() {
$.ajax({
type: "POST",
url: '/Survey/DoDetailSurvey?choiceId=1'
}
});
}
You can also pass like this
or for more parameters
function addCommentByAjax() {
$.ajax({
type: "POST",
url: '/Survey/DoDetailSurvey?choiceId=1&Name=Arun'
}
});
}

Ajax to WCF, can't load Ajax into an object

I want to send some data back form my JavaScript to WCF. This object I send back needs to get loaded in the Foo class. If I debug the code I can see the function (Sting) gets called. But if i check whats in the the object I got returned, this object is null.
This indicates the data can't be stored in in the Object of WCF. The WCF works find when I send data to the JavaScript with Ajax. FYI I use .NET 3.5
this is how I try to receive the data: WCF:
namespace TPlatform
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class DataService
{
[OperationContract]
public void Sting(Foo postData)
{
var x = 1; //Breakpoint, postData is null?
}
}
[DataContract]
public class Foo
{
[DataMember]
public string Bar;
}
}
JavaScript:
var fooObject = { "Bar": "test" };
function sendDataToWcf(object) {
$.ajax({
type: "POST",
url: "DataService.svc/Sting",
data: JSON.stringify(fooObject),
processData: false,
contentType: "application/json",
dataType: "json",
success: suckcess,
error: showError
});
}
What am I doing wrong? How can I read the the data into my class?
Try this
$.ajax({
type: 'POST',
url: url,
//dataType: 'json',
contentType: "application/json",
data: JSON.stringify({ postData: fooObject}),
success: function (response) {
successCallback(response);
},
error: function (xhr, status, error) {
handleError(xhr, status, error);
}
});
Update: Change:
var fooObject = { "Bar": "test" };
too
var fooObject = { Bar: "test" };
and dont send the datatype.

C# JSON Post From JavaScript

I have the following 2 classes which hold the data:
public class ItemList{
public IList<Item> Items{get;set;}
}
public class Item{
public int id {get;set}
public string name {get;set}
}
My controller looks like:
public virtual JsonResult SaveItems(ItemList items)
{}
I try to post a JS object like this:
var toPost = { "items" : [ {"id" : 1, "name":"test}, {"id" : 1, "name":"test"}] }
$.ajax({
type: "POST",
url: "URL TO POST TO",
dataType: "json",
data: toPost,
traditional: true,
success: function (data, status, request) {
if (data.Error != undefined) {
alert("System Error: " + data.Error);
return;
}
console.log("Success");
},
error: function (request, status, error) {
console.log("ERROR");
}
});
I do a console.log before i post it and the data looks as desribed in the toPost variable but when debugging on C# side the ItemList items is null
Use JSON.stringify in toPost and set the content type
$.ajax({
...
contentType: "application/json; charset=utf-8"
data: JSON.stringify(toPost),
...
});
Your SaveItems method is expecting an ItemsList object and what is being sent in the request is a string. You will need to deserialise the request data into your ItemsList object something like the following:
public virtual JsonResult SaveItems(String jsonRequest)
{
ItemsList items = Util.JsonSerializer.Deserialize<ItemsList>(jsonRequest);
// further processing of items
}

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