Passing JSON to Controller MVC3 C# .NET - c#

I´m trying to pass my data(json) from view through ajax to my controller but this arrive null. Thanks in advance fro any help or suggestion.
This is my model.
public class TipificacionModel
{
public int Existente { get; set; }
public string Campo { get; set; }
public int Regla { get; set; }
}
public class ListasSeleccionModel{
public List<string> DatosSeleccion { get; set; }
}
public class ListaTipificaciones
{
public string NombreCampaña { get; set; }
public List<TipificacionModel> Tipificacion { get; set; }
}
public class DatosSeleccionMultiple
{
public List<String> Columnas { get; set; }
public List<ListasSeleccionModel> ListasSeleccion { get; set; }
}
public class TipificacionGeneralCampaña
{
public ListaTipificaciones CamposCreados { get; set; }
public List<DatosSeleccionMultiple> ListasDeSeleccion { get; set; }
}
This is my ajax function.
jsonListaGeneral = [];
jsonListaGeneral.push(jsonTipificacion);
jsonListaGeneral.push(jsonListasSeleccion);
console.log(jsonListaGeneral);
$.ajax({
url: '#Url.Action("crearCampManual", "DPS")',
type: 'post',
data: JSON.stringify(jsonListaGeneral),
contentType: 'application/json; charset=utf-8;',
dataType: 'json',
success: function (response) {
alert(response)
return;
},
error: function (x) {
alert(x.responseText);
}
});
This is my controller.
[HttpPost]
public ActionResult crearCampManual(TipificacionGeneralCampaña model)
{ //Here the model value is null, why?}
When i print the json in my browser console everything is good. But something bad happends, im making something wrong.
Console Browser
Break Point Controller

One issue is that the data you are sending through your AJAX call appears to be an Array:
jsonListaGeneral = [];
But your C# model isn't an array or collection:
public ActionResult crearCampManual(TipificacionGeneralCampaña model)
If you are sending an array of TipificacionGeneralCampaña objects from your AJAX to your C# Controller, then you would want your Controller definition to look like this:
public ActionResult crearCampManual(List<TipificacionGeneralCampaña> model)
And also to reiterate what #Hackereman stated in his comment, you do not need to use the JSON.Stringify function on your data before you pass it to your Controller:
$.ajax({
url: '#Url.Action("crearCampManual", "DPS")',
type: 'post',
data: jsonListaGeneral,
contentType: 'application/json; charset=utf-8;',
dataType: 'json',
success: function (response) {
alert(response)
return;
},
error: function (x) {
alert(x.responseText);
}
});
Another issue that I noticed from your Console Browser screenshot: you seem to be adding two different objects to the same JSON array before sending to your controller:
jsonListaGeneral.push(jsonTipificacion);
jsonListaGeneral.push(jsonListasSeleccion);
When creating a collection in C#, all objects in the collect need to be of the same type, meaning that they have the same Property Names and Property Types.
With how your C# Controller is currently setup, it will accept a JSON object that is structured like this:
{
CamposCreados : {
NombreCampaña : "",
Tipificacion : [
{
Existente : 0,
Campo : "",
Regla : 0
},
{
Existente : 1,
Campo : "",
Regla : 1
}
]
}
ListasDeSeleccion : [
{
Columnas : "",
ListasSeleccion : [
{
DatosSeleccion : [
{
"",
"",
""
}
]
},
{
DatosSeleccion : [
{
"",
"",
""
}
]
}
]
}
]
}

The solution is change the declaration of the Json Object.
var jsonListaGeneral = {
"CamposCreados": jsonTipificacion,
"ListasDeSeleccion": jsonListasSeleccion
}

Related

Not getting data from ajax call to controller as array data in MVC c#

## AJAX CALL in cshtml page ##
function ValidateData() {
var editedRows = [];
$("#eventsTable tbody tr").each(function () {
editedRows.push({
PK_WS_Event: $(this).find("td:eq(1)")[0].innerText,
Act_Id: $(this).find("td:eq(2)")[0].innerText,
WeeklyStatus: $(this).find("td:eq(3) option:selected").text()
== "--Select--" ? "" : $(this).find("td:eq(3)
option:selected").text(),
WeeklyStatusSubType: $(this).find("td:eq(4)
option:selected").text() == "--Select--" ? "" : $(this).
find("td:eq(4) option:selected").text(),
AccountName: $(this).find("td:eq(5)")[0].innerText,
AccountNumber: $(this).find("td:eq(6)")[0].innerText,
WeeklyStatusDesc: $(this).find("td:eq(7)")
[0].textContent.trim(),
});
});
$.ajax({
type: 'post',
url: "/WeeklyStatus/IndexSubmit",
data: JSON.stringify({ editedRows: editedRows }),
contentType: 'application/json',
dataType: "html",
success: function (response) {
},
error: function (xhr, status, error) {
alert('fail');
}
});
}
## Server Code Controller and ##
----------
[HttpPost]
public IActionResult IndexSubmit(IList<WeeklyStatusEvents>
editedRows)
{
return null;
}
My ViewModel as like as below..
public class ReportViewModel
{
public int SelectedStatusId { get; set; }
public int SelectedSubTypeId { get; set; }
public List<WeeklyStatusEvents> statusEvents { get; set; }
}
And WeeklyStatusEvents model as shown below
public class WeeklyStatusEvents
{
public string PK_WS_Event { get; set; }
public string Act_Id { get; set; }
//public bool INDExcludeFromRpt { get; set; }
public string WeeklyStatus { get; set; }
public string WeeklyStatusSubType { get; set; }
public string AccountName { get; set; }
public string AccountNumber { get; set; }
public string WeeklyStatusDesc { get; set; }
}
So Here, I am getting count as 0......
I have created class with all these properties. and Same property name I was used in ajax call as well.
Even I am not getting data. Can you provide the solution what i missed to get the data.
Replace
data: JSON.stringify({ editedRows: editedRows }),
with
data: JSON.stringify(editedRows),
The difference is that you want to send an array of objects instead of an object which contains an array.
In order to see the diferences between those two, I recommend you to inspect what the following lines return:
console.log(JSON.stringify(editedRows)
console.log(JSON.stringify({ editedRows: editedRows })
And add [FromBody] in front of your parameter in your action.
Add [FromBody] in front of your List and try again
[HttpPost]
public ActionResult IndexSubmit([FromBody] List<WeeklyStatusEvents> obj)
{
Vreturn null;
}

Can't serialize/deserialize a list of objects from Javascript to C# .Net

I can currently serialize a single object in Javascript, post it via Ajax in Json and deserialize it in codebehind using a custom class as follows:
Javascript:
var ticket =
{
"aNumber" : 1,
"aString" : "foo"
};
jsonData = JSON.stringify(ticket);
$.ajax({
type: "POST",
url: url_webservice + "action",
data: "{obj:" + jsonData + "}",
contentType: 'application/json; charset=utf-8',
error: function (xhr, status, error) {
console.log(xhr.responseText);
},
dataType: "json"
});
Custom class:
public class Ticket
{
public int aNumber { get; set; }
public string aString { get; set; }
}
Codebehind:
[WebMethod]
public static void action(Ticket obj)
{
//do stuff
}
Now I want to accomplish the same but with several tickets as follows:
var tickets =
[
{
"aNumber" : 1,
"aString" : "foo"
},
{
"aNumber" : 2,
"aString" : "bar"
}
];
I tried to create a class by composition:
public class TicketsDTO
{
LinkedList<Ticket> tickets;
}
And then by inheritance:
public class TicketsDTO : LinkedList<Ticket>
{
}
None seems to work. I did update the argument of the WebMethod accordingly
[WebMethod]
public static void action(TicketsDTO obj)
{
console.log(""); //breakpoint
}
but the execution does not reach the breakpoint in these two cases and I don't get an error.
Any help is appreciated.

How to receive JSON data on WebAPI backend C#?

How do I receive JSON data on my WebAPI backend in C#?
I have the following JSON sent from my JavaScript frontend.
{
"User_Id": 1,
"TotalPrice": 35,
"DeliveryAddress": "At my house",
"CartItems": [
{
"Id": 1009,
"Name": "Superman juni 2014",
"Quantity": 1,
"Price": 35
}
]
}
I have this classes:
public class PurchaseOrder
{
public List<CartItem> CartItems { get; set; }
public string DeliveryAddress { get; set; }
public int TotalPrice { get; set; }
public int User_Id { get; set; }
}
public class CartItem
{
public int Id { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
public int Price { get; set; }
}
And my WebAPI method:
[System.Web.Mvc.HttpPost]
public bool AddOrder(PurchaseOrder order)
{
// Here I will do something
return true;
}
I only get "null" as the result for my "PurchaseOrder order" object. Can the problem be that I´m using [System.Web.Mvc.HttpPost]? I have also tried [System.Web.Http.HttpPost], but get the same result.
// Martin
The Content-Type of your request should be "application/json"
If you post your json in a body of the request than change a method signature to
[HttpPost]
public bool AddOrder([FromBody] PurchaseOrder order)
{
}
Problem solved, it was the "application/json" that was missing. For other persons having the same problem, here is my function. I´m using Knockout.js, hence the "self"-word.
self.makePurchase = function () {
var tempUserId = self.orderUserId();
var tempCartPrice = self.ShoppingCartPrice();
var tempAddress = self.orderAddress();
var tempCart = self.ShoppingCart();
var orderSave = new PurchaseSave(tempUserId, tempCartPrice, tempAddress, tempCart);
var myData = ko.toJSON(orderSave);
console.log(myData);
$.ajax({
type: "POST",
async: false,
url: '/Products/AddOrder',
contentType: "application/json", // Thank you Stackoverflow!!!
dataType: "json",
traditional: true,
data: myData,
error: function (xhr, textStatus, errorThrown) {
console.log(xhr.responseText);
console.log("Inside the error method");
},
success: function (data) {
console.log("Inside the success method");
}
});
}
Change your implementation to this.
[System.Web.Http.HttpPost]
public bool AddOrder([FromBody] PurchaseOrder order)
{
}
For more details - http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
Try using Newtonsoft.Json package from NuGet. They have functions to serialize and deserialize any string to Json.
Also try using dynamic type variables. Helps for deserializing.

JSON passing as a null to a method argument

I finally tried to try my hand at using KnockoutJS. I explored for shorter ways to send JSON data to a C# method in MVC 4, but ended up using the AJAX method instead. I have some confusion around the following and was hoping someone could help.
Javascript
var VM = function () {
var self = this;
self.ValidateAndCreate = function () {
console.log("entered");
var a = {
b: "1",
c: "2",
d: {
e: "3"
}
};
var input = { data: a }
console.log(JSON.stringify(input));
$.ajax({
url: '/McAfee/ValidateAndCreatePartner',
data: JSON.stringify(input),
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
console.log('success');
}
});
}
}
var viewModel = new VM();
ko.applyBindings(viewModel);
C#
[HttpPost]
public void ValidateAndCreatePartner(string data)
{
var x = JsonConvert.DeserializeObject(data);
RedirectIfSuccess();
}
What currently happens is that the ValidateAndCreatePartner fires, but the argument data is null, followed by NewtonSoft.Json.JsonConvert.DeserializeObject failing as a result. How can I resolve this issue?
The easiest way in MVC is to create class as per your data : it is much cleaner! For example, with your example, you can try this :
[HttpPost]
public ActionResult Test(TestClass data) {
RedirectIfSuccess();
}
public class TestClass
{
public string b { get; set; }
public string c { get; set; }
public TestSubClass d { get; set; }
}
public class TestSubClass
{
public int e { get; set; }
}
Since your content type is application/json, the argument to the view function will be automatically deserialized (it's not a string anymore).
Create a viewmodel on the server side matching the one you send and use it as the type argument of the view:
public class D {
public string e {get;set;}
}
public class A {
public string b {get;set;}
public string c {get;set;}
public D d {get;set;}
}
[HttpPost]
public void ValidateAndCreatePartner(A data)
{
// no need to deserialize data
RedirectIfSuccess();
}

Submit Form with Complex DataType to Controller

This is my model
Model
public class XPersonContent
{
public string PersonType { get; set; }
public int PersonId { get; set; }
}
public class XViewModel
{
public List<XPersonContent> XPersonList { get; set; }
public string XContent { get; set; }
public sbyte CommentEnabled { get; set; }
}
Controller
[HttpPost]
public JsonResult AddXViewModel ( XViewModel testModel)
{
}
Form using MVC that submits to controller
function submitForm() {
var xpersonContent=[Object { Id=2934109, Type="us"}, Object { Id=2913974, Type="us"}, Object {Id=2912159, Type="us"}]
var xContent= "test";
var CommentEnabled= false;
var dataString = {
XPersonList:xpersonContent,
XContent: xContent,
CommentEnabled: true
};
$.ajax({
type: "POST",
url: "/AjaxPostDemo/AddXViewModel",
data: JSON.stringify(dataString ),
cache: false,
dataType: "json",
success: function (data) {
$("#ajaxPostMessage").empty();
$("#ajaxPostMessage").html(data.Message + " : " + data.Date);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
}
> Question
How do i build the object XViewModel to pass back to the controller. i have them in three different variables
i have tried to do this
dataString = {
XPersonList:xpersonContent,
XContent: xContent,
CommentEnabled: true
};
but its not working..
I had to add
contentType: "application/json; charset=utf-8",
in my ajax request
SMH
Try change to this
var xpersonContent=[{"XPersonContent": {"Id": 2934109, "Type": "us"}}, {"XPersonContent": {"Id": 2913974, "Type": "us"}}, {"XPersonContent": {"Id": 2912159, "Type": "us"}}]

Categories

Resources