Passing Json Map to MVC controller using ajax - javascript

I need to pass map (dictionary) to the MVC controller along with a string parameter.
var reportName= 'ReportName';
var FilterValues = new Map([
[0, "value1"],
[1, "value2"],
[2, "value3"],
]);
var model = { reportName: reportName, FilterValues: JSON.parse(FilterValues) };
$.ajax({
url: '/Reports/ExportReport/',
type: 'POST',
contentType: "application/json",
data: model,
success: function(){
alert('success');
},
error: function(){
alert('failure');
}
});
public void ExportReport(string reportName, Dictionary<int, string> FilterValues)
{
Also tried this with Object instead of map . It returns me a success but doesn't hit the controller.
let FilterValues = {
1: "value1",
2: "value2",
3: "value3",
};
var report = 'test';
// var data = ('#DesignationReport').DataTable().$('input,select,textarea').serialize();
var model = { reportName: report, FilterValues: FilterValues };
This is the last thing I tried.

Since JSON does not support ES2015 constructs such as Map. We need to have custom class as bellow:
public class ViewModel
{
public List<FilterValue> FilterValues { get; set; }
public string ReportName { get; set; }
}
public class FilterValue
{
public int Id { get; set; }
public string Value { get; set; }
}
Your post method will be:
[HttpPost]
public ActionResult ExportReport(ViewModel model)
{
var report = model.ReportName;
var values = model.FilterValues;
return new EmptyResult();
}
Then view's scripts will be:
#section scripts{
<script>
$(function () {
var reportName = 'ReportName';
var filterValues = [];
filterValues.push({ 'Id': 0, 'Value': 'value1' });
filterValues.push({ 'Id': 1, 'Value': 'value2' });
filterValues.push({ 'Id': 2, 'Value': 'value3' });
var model = JSON.stringify({ ReportName: reportName, FilterValues: filterValues});
$.ajax({
url: '/Home/ExportReport/',
type: 'POST',
contentType: "application/json",
data: model,
success: function () {
alert('success');
},
error: function () {
alert('failure');
}
});
});
</script>
}

Set up your model in MVC like this
public class SpecialDataModel
{
public string reportName { get; set; }
public List<SingleFilterValue> FilterValues { get; set; }
}
public class SingleFilterValue
{
public int id { get; set; }
public string value{ get; set; }
}
Set up your controller method like this
[HttpPost]
public void ExportReport(SpecialDataModel myData)
{
}
Set up your data for your ajax data property like this
var reportName= 'ReportName';
var FilterValues = [];
FilterValues.push({'id': 0, 'value': 'value1'});
FilterValues.push({'id': 1, 'value': 'value2'});
FilterValues.push({'id': 2, 'value': 'value3'});
var model = JSON.stringify({ 'reportName' : reportName, 'FilterValues' : FilterValues });

Related

How can I validate my model when I have an array property?

I have a class with an array property in MVC
public class MyClass
{
public int Contrato_Id { get; set; }
public string Contrato { get; set; }
public int Torre_Id { get; set; }
public string Torre { get; set; }
public SkillsATB[] Skills { get; set; }
}
When I do the POST via jquery ajax my ModelState validation is always false
if (ModelState.IsValid)
{
var _current = _Service.Insert(current);
return Json(new { result = "success", resultValue = "" });
}
debuggin image here here
The property SkillsATB is ok, it has elements, but I think I am missing something for that array.
function ConvertToSkillsObject(id, name) {
var skill = {
Id: Math.round(id),
Nombre: name,
Descripcion: "",
Activo: "1",
Asignada: 1
}
return skill;
}
function GetSkillsAsignados() {
var asignados = [];
$("#sortable2").children().each(function () {
var item = ConvertToSkillsObject($(this).attr("data-id"), $(this).html())
asignados.push(item);
});
return asignados;
}
var MyClass= {
Correo: $('#correo').val(),
CorreoLider: $('#correoLider').val(),
CorreoLiderBSD: $('#correoLiderBSD').val(),
FechaNacio: $('#fechaNacio').val(),
Contrato_Id: $('#contrato_Id').val(),
Torre_Id: $('#torre_Id').val(),
Skills: GetSkillsAsignados()
};
$.ajax({
url: "../../MyController/Save",
type: "POST",
data: JSON.stringify(MyClass),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (e) {
... //more javascript
Remove the property from the model before validating: ModelState.Remove("Skills");
SOLVED
The problem was in a datepicker CSS, something was wrong in the format date. Nothing to do with the prior before

Controller recieving empty data from Ajax

I'm trying to send a collection from a view to a controller, using ajax. First I complete the data in a javascript array, and then I try to pass it to the server:
var funciones = $("#funcionesUsuario").data("kendoGrid").dataSource.data();
var func = [];
for (var i = 0; i < funciones.length; i++) {
func.push({
"Estado": 1,
"FechaAlta": null,
"UsuarioAlta": null,
"FechaModificacion": null,
"UsuarioModificacion": null,
"BitConcilia": funciones[i].BitConcilia,
"BitLectura": funciones[i].BitLectura,
"BitSupervisa": funciones[i].BitSupervisa,
"ConciliacionId": funciones[i].ConciliacionId,
"UsuarioId": funciones[i].UsuarioId
})
}
$.post(url, { funcionesUsuario: func })
.done(function (data) {
alert("good job");
});
Then, since I'm sending data for 2 objects, my parameter is a IEnumerable of said object:
public void ActualizarFuncionesUsuario(IEnumerable<FuncionUsuario> funcionesUsuario)
{
//do something
}
My problem is that the controller receives 2 objects, as I can see in the funcionesUsuario.count, but they are both empty.
I tried sending int, bool and other types of variables with success, so I suspect I'm doing something wrong regarding data binding.
Below I attached pictures of what I'm sending and what I'm receiving in the other side.
This is the FuncionUsuario model: `
public class FuncionUsuario : AuditableEntity {
public int ConciliacionId { get; set; }
public int UsuarioId { get; set; }
public bool BitLectura { get; set; }
public bool BitConcilia { get; set; }
public bool BitSupervisa { get; set; }
public virtual Conciliacion Conciliacion { get; set; }
[Display(ResourceType = typeof(Global), Name = "Descripcion")]
[NotMapped]
public string Descripcion { get; set; }
}
first construct you array as java script objects
var funciones = $("#funcionesUsuario").data("kendoGrid").dataSource.data();
var func = [];
for (var i = 0; i < funciones.length; i++) {
func.push({
Estado: 1,
FechaAlta: null,
UsuarioAlta: null,
FechaModificacion: null,
UsuarioModificacion: null,
BitConcilia: funciones[i].BitConcilia,
BitLectura: funciones[i].BitLectura,
BitSupervisa: funciones[i].BitSupervisa,
ConciliacionId: funciones[i].ConciliacionId,
UsuarioId: funciones[i].UsuarioId
})
}
Next, properly stringify them
var payload = JSON.stringify(func);
Then post it as JSON
$.ajax({
url: url,
type: "POST",
contentType: "application/json",
dataType: 'json'
data: payload,
});
Try these:
Specify json as the dataType
$.post(url, { funcionesUsuario: func })
.done(function (data) {
alert("good job");
}, 'json');
Use $.ajax instead: docs
$.ajax({
url: url,
data: JSON.stringify(func),
contentType: "application/json",
type: "POST"
});

Send Array of Objects from JavaScript to C# controller

I was trying several ways to pass the list of objects to the controller but
the controller always receives null
Here is my code:
View:
$('#btnSave').click(function () {
var arrPropIdPos = new Array();
$('.property').each(function () {
var obj = {
PropertyId : $(this).attr('PropertyId'),
Xposition : $(this).attr('xPos'),
Yposition : $(this).attr('yPos')
};
arrPropIdPos.push(obj);
});
var jsonData = JSON.stringify(arrPropIdPos);
$.ajax({
url: "/PropertyPosition/Insert/",
type: 'POST',
data: jsonData,
dataType: 'json',
//...
},
console.log(arrPropIdPos);
0: Object
PropertyId: "1"
Xposition: "11"
Yposition: "55"
__proto__: Object
1: Object
PropertyId: "2"
Xposition: "651"
Yposition: "48"
__proto__: Object
console.log(jsonData);
[{"PropertyId":"1","Xposition":"11","Yposition":"55"},
{"PropertyId":"2","Xposition":"651","Yposition":"48"}]
Controller (option 1):
[HttpPost]
public JsonResult Insert(string jsonData)
{
// jsonData is null
}
Controller (option 2):
public class PropertyPositionInsert
{
public string PropertyId { get; set; }
public string Xposition { get; set; }
public string Yposition { get; set; }
}
public JsonResult Insert(List<PropertyPositionInsert> model)
{
// model is null
}
Try to wrap your array into an object with a property model:
var jsonData = JSON.stringify({model: arrPropIdPos});
Also try to set dataType option to 'application/json'.
$('#btnSave').click(function () {
var arrPropIdPos = new Array();
$('.property').each(function () {
var obj = {
'PropertyId' : $(this).attr('PropertyId')
,'Xposition' : $(this).attr('xPos')
,'Yposition' : $(this).attr('yPos')
};
arrPropIdPos.push(obj);
});
$.ajax({
type: 'POST',
contentType: "application/json",
data: JSON.stringify(arrPropIdPos),
url: "/PropertyPosition/Insert/"
});
Class:
public class PropertyPositionInsert
{
public string PropertyId { get; set; }
public string Xposition { get; set; }
public string Yposition { get; set; }
}
Controller:
public JsonResult Insert(PropertyPositionInsert[] model)
{
}
I have run into this in the past and have found that if you set
traditional: true
in your jQuery ajax call, it shjould fix the issue.
$('#btnSave').click(function () {
var arrPropIdPos = new Array();
$('.property').each(function () {
var obj = {
PropertyId : $(this).attr('PropertyId'),
Xposition : $(this).attr('xPos'),
Yposition : $(this).attr('yPos')
};
arrPropIdPos.push(obj);
});
var jsonData = JSON.stringify(arrPropIdPos);
$.ajax({
beforeSend: function () {
},
type: "POST",
"async": true,
url: "/PropertyPosition/Insert/",
data: JSON.stringify(obj),
dataType: "json",
contentType: "application/json",
success: function (data) {
},
error: function (xhr, textStatus, error) {
},
complete: function () {
},
})
Controller:
Create a class or model
public class PropertyPositionInsert
{
public string PropertyId { get; set; }
public string Xposition { get; set; }
public string Yposition { get; set; }
}
public IHttpActionResult JsonResult (PropertyPositionInsert obj)
{
obj.PropertyId;
obj.Xposition ;
obj.Yposition;
}
you can check the values in above obj

How to pass array in a JSON object from javascript to asp.net mvc controller method?

My model:
public class Company
{
[BsonElement]
[BsonRepresentation(MongoDB.Bson.BsonType.String)]
public String PlaceId { get; set; }
[BsonElement]
[BsonRepresentation(MongoDB.Bson.BsonType.String)]
public string Name { get; set; }
[BsonElement]
[BsonRepresentation(MongoDB.Bson.BsonType.String)]
[BsonIgnoreIfNull]
public string Email { get; set; }
[BsonElement]
[BsonRepresentation(MongoDB.Bson.BsonType.Double)]
public Double Rating { get; set; }
[BsonElement]
[BsonIgnoreIfNull]
public Department Department { get; set; }
[BsonElement]
[BsonIgnoreIfNull]
public Product Product { get; set; }
[BsonElement]
public Comment[] Comments { get; set; }
}
public class Comment
{
[BsonElement]
public String Text { get; set; }
}
My controller method:
public JsonResult SavePlace(Company company)
{
if (company != null)
{
var client = new MongoClient("mongodb://localhost");
var database = client.GetDatabase("mongogoogleplace");
var placeData = database.GetCollection<BsonDocument>("googledatanew");
var department = company.Department.ToBsonDocument();
var product = company.Product.ToBsonDocument();
//var comments = company.Comments.ToBsonElement();
var companyModel = company.ToBsonDocument();
var filter = Builders<BsonDocument>.Filter.Eq("PlaceId", company.PlaceId);
var projection = Builders<BsonDocument>.Projection
.Exclude("_id");
//BsonDocument document = new BsonDocument();
var document = placeData.Find(filter).Project(projection).FirstOrDefault();
var documentJson = document.ToJson();
return Json(documentJson);
}
else
{
return Json(new { data = "error." });
}
}
Javascript snippet:
var company = { "PlaceId": PlaceId, "Name": Name, "Rating": Rating, "Comments": [{ Comment: { Text: '' } }, { Comment: { Text: '' } }, { Comment: { Text: '' } }, { Comment: { Text: '' } }, { Comment: { Text: '' } } ] };
for (var i = 0; i < CommentsArray.length; i++) {
company.Comments[i].Comment.Text = CommentsArray[i];
};
$.ajax({
type: "POST",
url: "../Home/SavePlace",
data: company,
// dataType: "json",
success: function (data){}
But every time I get the comments to be null.
In your data you need to convert object to JSON in this way:
data: JSON.stringify(company)
Now in your method you should be able to get the comments. Another way is this:
data: { company: company }
Where the first name must be the same as your parameter name in the action method. I'm not sure at 100% that works because I'm not sure that company will be converted to a C# object correctly.
Change:
data: company
To
data : {company: company}
The Action expects an object with a parameter named company.
Your Action must look like this:
[HttpPost]
public JsonResult SavePlace(Company company)
{
// Your code
}
Your Ajax request:
$.ajax({
type: "POST",
url: "../Home/SavePlace",
data: JSON.stringify(company),
contentType: "application/json; charset=utf-8",
success: function (data){}
});
Define your company object like this:
var company = {
PlaceId: "XXXX",
Name: "XXXX",
Rating: 10.0,
Comments: [
Comment: { Text: '' },
Comment: { Text: '' },
Comment: { Text: '' },
Comment: { Text: '' },
Comment: { Text: '' }
]
};
Here is a complete working example.
The code of the view:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var company = {
PlaceId: "XXXX",
Name: "XXXX",
Rating: 10.0,
Comments: [
Comment: { Text: '' },
Comment: { Text: '' },
Comment: { Text: '' },
Comment: { Text: '' },
Comment: { Text: '' }
]
};
$(document).ready(function(){
$("#toto").on("click", function () {
$.ajax({
type: "POST",
url: "../Home/SavePlace",
data: JSON.stringify(company),
contentType : "application/json; charset=utf-8",
dataType: "json",
});
});
});
</script>
<input type="button" id="toto" />
The c# and controller code:
public class HomeController : Controller
{
public ActionResult Index()
{
return this.View();
}
[HttpPost]
public JsonResult SavePlace(Company company)
{
if (company != null)
{
return Json(new { data = "fine." });
}
else
{
return Json(new { data = "error." });
}
}
}
public class Company
{
public String PlaceId { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public Double Rating { get; set; }
public object Department { get; set; }
public object Product { get; set; }
public Comment[] Comments { get; set; }
}
public class Comment
{
public String Text { get; set; }
}

Sending complex object in ajax to MVC

The value of List<Order> returns as null in my controller action method while sending the complex object. Can someone help to identify the issue? Do we need to pass array of objects with indexes?
JavaScript
function OnCustomerClick() {
//var orders = [];
//orders.push({ 'OrderId': '1', 'OrderBy': 'Saroj' });
var complexObject = {
FirstName: 'Saroj',
LastName: 'K',
//Orders : orders
Orders: [{ OrderId: 1, OrderBy: 'Saroj' }, { OrderId: 2, OrderBy: 'Kumar' }]
};
var obj = { customer: complexObject };
var data2send = JSON.stringify(obj);
$.ajax({
type: "POST",
url: 'Home/TestCustomer1',
data: data2send,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (arg) { //call successfull
},
error: function (xhr) {
//error occurred
}
});
};
MVC
public ActionResult TestCustomer1(Customer customer)
{
return Json(customer);
}
C#
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
List<order> Orders { get; set; }
}
public class order
{
public int OrderId { get; set; }
public string OrderBy { get; set; }
}
You need to use public properties for model binding. Orders currently has no access modifier, so its private.
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public List<order> Orders { get; set; } // <----
}
Other than that, everything looks fine.

Categories

Resources