ajax pass object to controller - c#

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

Related

How to make post call to c# pagemodel class

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

Call the controller method using Ajax

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

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

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

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