Passing JSON Object from Javascript to ASP.Net - c#

I am trying to pass the Json string sObject from javascript to c#. In c# I am trying to load data from this JSon string to a Object.
I get a Bad Request error in Javascript.
C# Entity Object:
public class StatusEntity
{
public string WorkOrderID { get; set; }
public string JobID { get; set; }
public string ClientID { get; set; }
}
c# WCF Service:
[WebInvoke(UriTemplate = "/updatestatus", Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
public string updateStatus(List<StatusEntity> _objStatus)
{
string sResult = string.Empty;
try
{
// SOME CODE HERE
}
catch (Exception)
{
sResult = string.Empty;
throw;
}
finally
{
}
return sResult;
}
Javascript Code:
function updateStatus() {
var sObject = '[{"WorkOrderID":"9","JobID":"48","ClientID":"9"},{"WorkOrderID":"9","JobID":"48","ClientID":"10"}]';
$.ajax({
cache: false,
type: "POST",
async: false,
url: "../JobMatchingService/updatestatus",
contentType: "application/json; charset=utf-8",
dataType: "json",
// OLD CODE - NOT WORKING
data: sObject,
// NEW CODE CHANGES WORKING
data: '{"_objStatus":' + _objStatus + '}',
success: function (response) {
alert(response);
},
error: function (xhr, options, error) {
alert(error);
}
});
}

Change _objStatus to a string in the method parameter, then use a try/catch to transform it into a StatusEntity like so:
var status = JsonConvert.DeserializeObject<List<StatusEntity>>(jsonString);

Made changes to the javascript, the data has to specified as below:
// OLD CODE - NOT WORKING
data: sObject,
// NEW CODE CHANGES WORKING
data: '{"_objStatus":' + _objStatus + '}',
function updateStatus() {
var sObject = '[{"WorkOrderID":"9","JobID":"48","ClientID":"9"},{"WorkOrderID":"9","JobID":"48","ClientID":"10"}]';
$.ajax({
cache: false,
type: "POST",
async: false,
url: "../JobMatchingService/updatestatus",
contentType: "application/json; charset=utf-8",
dataType: "json",
// OLD CODE - NOT WORKING
data: sObject,
// NEW CODE CHANGES WORKING
data: '{"_objStatus":' + _objStatus + '}',
success: function (response) {
alert(response);
},
error: function (xhr, options, error) {
alert(error);
}
});
}

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

How to get return value of WebMethod from JQuery

I am tryring to get the return value of WebMethod from JQuery call, but I am getting "undefined" message. Here is my code below
$.ajax({
type: "POST",
url: "Receipt/BarcodeEntered",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function (msg) {
alert(msg.d); // This displays "Undefined"
alert(msg); // This displays the whole html
}
});
and the WebMethod is below
[WebMethod]
public static string BarcodeEntered()
{
return "test_string";
}
how can I get the value from WebMethod and display it on client side?
WebMethod officialy only can return XML or JSON.
Default is json, so whatever you return gets converted to json
change in JQuery dataType: "json",
$.ajax({
type: "POST",
url: "Receipt/BarcodeEntered",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg);
}
});
and you should return class not single string. because string can not be converted valid json object.
public class SampleClass{
public string Message {set; get;}
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public SampleClass BarcodeEntered()
{
return new SampleClass(){
Message = "Sample message"
};
}
You need to return JSON, let me write down an example.
public JsonResult DoStuff()
{
string text = "text";
return Json(text, JsonRequestBehavior.AllowGet);
}
Here is the working demo I am using this in my asp.net page. The data is will be in d property.
JQuery code.
$.ajax({
type: "POST",
url: "/Subfolder/MyPageName.aspx/myWebMethodName",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if (msg.d == "OK") {
alert("OK")
} else {
alert(msg.d);
}
}
});
C# Code
[WebMethod]
public static string myWebMethodName()
{
return "OK";
}

jQuery is not firing backend method in asp.net

I am firing Backend method of asp.net using jQuery. I have set everything perfectly as much i knew. But still don't know what is the wrong.
Please help me to solve this issue.
My Code :
<asp:Button ID="btnSubmit" runat="server" Text="Update" />
var jquery = $.noConflict();
jquery(document).ready(function() {
jquery("#<%=btnSubmit.ClientID%>").click(function() {
if(jquery("#form1").valid()) {
jquery.ajax({
type: "POST",
url: "Page.aspx/UpdateData",
data: jquery("#form1").serialize(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
},
error: function(msg) {
alert(msg);
}
});
}
});
});
Backend method :
[System.Web.Services.WebMethod]
public static string UpdateData(string get_param)
{
// Code...
}
I also tried to check by using BeakPoint but it is not going in code behind. Even, I can't see any error.
I removed content type. As you are using formSerialize. It will form data like key=value&key1=value1 and it is not json format so.
note: Make sure you have form with id form1 present.
jquery(document).ready(function() {
jquery("#<%=btnSubmit.ClientID%>").click(function() {
if(jquery("#form1").valid()) {
jquery.ajax({
type: "POST",
url: "Page.aspx/UpdateData",
data: '{ "get_param" :"' + $('form').serialize() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
},
error: function(msg) {
alert(msg);
}
});
}
});
});
try to remove contentType from ajax request anf get dataa
public static string UpdateData(string get_param)
string get_params= HttpContext.Current.Request["get_param"];
}
If you want to send json data, convert your data to json format.
var jquery = $.noConflict();
jquery(document).ready(function() {
jquery("#<%=btnSubmit.ClientID%>").click(function() {
if(jquery("#form1").valid()) {
jquery.ajax({
type: "POST",
url: "Page.aspx/UpdateData",
data: JSON.stringify({ get_param:jquery("#form1").serialize() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
},
error: function(msg) {
alert(msg);
}
});
}
});
});
public class MyClass
{
public string myName
{
get { return "Hello"; }
}
}
In your aspx.cs page:
[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json, UseHttpGet = true)]
public static object MyMethod()
{
return new MyClass();
}
And in your ASPX page:
$.ajax({
url: "somepage.aspx/MyMethod",
data: {},
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "GET",
success: function (data) {
if (data.hasOwnProperty("d"))
alert(data.d.myName);
else
alert(data);
},
error: function (reponse) {
alert(reponse);
}
});
Issue was because of asp.net button. It was refreshing page after validation completion. So, I used preventDefault after button click in jquery and it has solved my issue.
Check my code :
function pageLoad() {
jquery('#<%= btnSubmit.ClientID %>').click(function (e) {
if(jquery("#form1").valid()) {
e.preventDefault(); // this line was imp
// Ajax call...
});
}

ajax pass object to controller

HomeController:
[HttpPost]
public JsonResult SetDefaultHomeCategoryOrder(CategoryOrderModel categories)
{
return Json(new { msg = "ok" });
}
public class CategoryOrderModel
{
public int DisplayOrder;
public int CategoryId;
}
View:
var operationCollection = new CategoryOrderModel();
$.ajax({
url: '#Url.Action("SetDefaultHomeCategoryOrder", "Home")',
dataType: 'json',
data: JSON.stringify(operationCollection),
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.msg);
},
error: function (data) {
alert('error');
}
});
The controller never gets the correct parameter??
UPDATED: I changed the code to accept the collection
[HttpPost]
public JsonResult SetDefaultHomeCategoryOrder(List<CategoryOrderModel> categories)
{
return Json(new { msg = 'ok' });
}
View:
var collection = [];
var col1= new CategoryOrderModel(1,2);
collection.push(col1);
var col2= new CategoryOrderModel(2,5);
collection.push(col2);
$.ajax({
url: '/Home/SetDefaultHomeCategoryOrder/',
dataType: 'json',
data: '{ categories : ' + JSON.stringify(collection) + '}',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.msg);
},
error: function (data) {
alert('error');
}
});
function CategoryOrderModel(displayOrder, categoryId) {
var self = this;
self.DisplayOrder = displayOrder;
self.CategoryId = categoryId;
}
Following are the errors in your code
1.Your model dont have getters and setters
public class CategoryOrderModel
{
public int DisplayOrder { get; set; }
public int CategoryId { get; set; }
}
2.Since it is javascript , operationCollection is model so it will not work instead deaclare a variable
var CategoryOrderModel =
{
"DisplayOrder": "7",
"CategoryId": "9"
};
$.ajax({
url: '#Url.Action("SetCategoryOrder", "Home")',
dataType: 'json',
data: '{ categories : ' + JSON.stringify(CategoryOrderModel) + '}',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.msg);
},
error: function (data) {
alert('error');
}
});
As we know MVC works on the principle of name/value pair i.e. on Strongly type view along with Model binding.
Possibly you can do:
$.ajax({
url: '#Url.Action("SetDefaultHomeCategoryOrder", "Home")',
dataType: 'json',
data: {'DisplayOrder' : 9 , 'CategoryId' : 1},
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.msg);
},
error: function (data) {
alert('error');
}
});
Notice data key/value data: {'DisplayOrder' : 9 , 'CategoryId' : 1},, this is somewhat similar to post a form in MVC.
Generally we use $('#formId').serialize() to send collection from view to controller with jquery/ajax.
You are trying to pass the data to controller "SetDefaultHomeCategoryOrder" or "SetCategoryOrder"
if Action name is SetCategoryOrder then type
url:#Url.Action('SetCategoryOrder','Home')
Your methods don't match from view you are calling SetDefaultHomeCategoryOrder but inside the controller it's called SetCategoryOrder

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.

Categories

Resources