I write this java script to send json object to c# web service. but its not work..Why is it?
this is my javascript..
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery- 1.5.1.js"></script>
<script type="text/javascript">
function BindJson() {
document.getElementById("demo").innerHTML=Date();
$.ajax({
type: "POST",
url: "Service1.asmx/SerializeJson",
data: JSON.stringify({ person:{ firstName: "Denny" }}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data2) {
alert(data2.d);
},
error: function (request, status, errorThrown) {
alert(status);
}
});
}
</script>
And this is my server class ..
[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public string SerializeJson(Person person)
{
return "Success";
}
public class Person
{
public string firstName { get; set; }
}
}
You should not use JSON.stringify because when you specify content type of JSON, jQuery will convert it using JSON.stringify.
data: JSON.stringify({ person:{ firstName: "Denny" }}),
contentType: "application/json; charset=utf-8",
dataType: "json",
Change it to
data: { person:{ firstName: "Denny" }},
contentType: "application/json; charset=utf-8",
dataType: "json",
Also you don't need to send person as a member of object unless it is required.
data: { firstName: "Denny"},
contentType: "application/json; charset=utf-8",
dataType: "json",
data option for .ajax expects a name value pair string, or an object
data: { "myjson": JSON.stringify({ person:{ firstName: "Denny" }}) },
//OR
data: "myjson="+JSON.stringify({ person:{ firstName: "Denny" }}),
//Or just send the data values and retrieve in the way you get GET or POST variables in C#
data: { person:{ firstName: "Denny" }},
Related
I've a c# class like below sample code
public class IndexModel : PageModel
{
public JArray Transactions { get; set; }
public IActionResult OnPostTranJarray(int transaction_number, string cardholder)
{
dynamic Trans = GetTransactions(transaction_number,cardholder);
return Trans;
}
}
i just wanted to Make a post call inside the IndexModel Class.
I've use these below code in jquery
$.post("https://localhost:7197/Transactions?handler=TranJarray?transaction_number="+transactionNumb+"&cardholder="+cardHolderName, response => {
alert("response",response);
});
$.ajax({
type: "POST",
url: "https://localhost:7197/Transactions?handler=TranJarray?transaction_number="+transactionNumb+"&cardholder="+cardHolderName,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (data)
{
alert("success");
fnLoadTbl();
}
});
But it's not hitting to the method.. but if i make GET Request to some other method in that class it's working. so let me know if you have any idea. Thanks..
You can use data parameter.
Try this:
var yourUrl= "https://localhost:7197/Transactions"; //pure action
var feed = {
transaction_number: yourNumber,
cardHolderName: yourString
};
$.ajax({
type: "POST",
url: yourUrl,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: feed,
async: true,
cache: false,
success: function (data) {
alert("success");
fnLoadTbl();
}
});
I am trying to call a controller's method by using ajax but somehow I am unable to call the method. I am sending an array type object as a parameter to post but not getting the value of the parameter on the controller, Even I send the parameter as JSON.stringify but the problem still exists.
Here is my ajax method.
$('.btn-generate-bill').on('click', function(event) {
event.preventDefault();
const billArray = [];
$('.posTable').find('tbody tr').each(function(index, elem) {
billArray.push({
ProductID: $(elem).find('.productID').text().trim(),
Quantity: $(elem).find('.qtyControl').val()
});
})
console.log(JSON.stringify(billArray));
$.ajax({
url: "/Cashier/UpdateProductQuantity",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
pDetail: JSON.stringify(billArray)
},
responseType: "json",
cache: false,
traditional: true,
async: false,
processData: true,
success: function(data) {
alert('success');
}
});
})
Here is the controller's method.
public JsonResult UpdateProductQuantity(List<Test> pDetail)
{
return Json("", JsonRequestBehavior.AllowGet);
}
public class Test
{
public int ProductID { get; set; }
public int Quantity { get; set; }
}
I think there are 2 points to be fixed :
ajax without the type will become a GET request. Put POST
try using data: JSON.stringify({ 'pDetail': billArray})
So, it becomes :
$.ajax({
url: "/Cashier/UpdateProductQuantity",
type : 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ 'pDetail': billArray}),
responseType: "json",
success: function (data) {
alert('success');
}
});
I would try FromBody with your controller:
[HttpPost]
public JsonResult UpdateProductQuantity([FromBody]List<Test> pDetail)
{
return Json("", JsonRequestBehavior.AllowGet);
}
You said you needed to post your billArray so your ajax request should be a post type like this:
$.ajax({
url: "/Cashier/UpdateProductQuantity",
type : 'POST', //this is the difference
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ 'pDetail': billArray}),
responseType: "json",
success: function (data) {
alert('success');
}
});
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";
}
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...
});
}
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