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
Related
I get this result from creating JSON in my view
header:{"ScheduledVisit":"08/02/2017 12:00 AM","Company":"fdsa","ContactPerson":"asfd","Phone":"asdf","Purpose":"fasd","Detail":"asdf"}
My model looks like this:
public class ScheduleVisit
{
[Required(ErrorMessage = "* Required")]
public DateTime ScheduledVisit { get; set; }
public string Company { get; set; }
public string ContactPerson { get; set; }
public string Phone { get; set; }
public string Purpose { get; set; }
public string Detail { get; set; }
}
I pass my data like so:
document.getElementById("btn_submit_schedule").addEventListener("click", function (event) {
event.preventDefault();
if ($("#scheduledVisit").val().length === 0) {
$("#scheduledVisit").focus();
}
var obj = {};
obj.ScheduledVisit = document.getElementById("scheduledVisit").value;
obj.Company = document.getElementById("company").value;
obj.ContactPerson = document.getElementById("contactPerson").value;
obj.Phone = document.getElementById("phone").value;
obj.Purpose = document.getElementById("purpose").value;
obj.Detail = document.getElementById("detail").value;
console.log(obj);
addSchedule(obj);
});
function addSchedule(data) {
$.ajax({
type: "POST",
url: "#Url.Action("ScheduleVisit", "ScheduleVisit")",
data: {header: JSON.stringify(data)},
success: function(result) {
alert(result);
},
error: function(error) {
alert(error);
}
});
}
and my controller looks like this:
[HttpPost]
public JsonResult ScheduleVisit(ScheduleVisit header)
{
return Json(false);
}
When I run in debug mode and check if my controller accepts anything, I get null on the "header" parameter. Please show me where I am getting it wrong.
Just replaced data: {header: JSON.stringify(data)} with data: data with current solution.
This very complex and manual way you'll can use simple way as following
Assign name field to every element as same like id now
<input type="text" name="Company" value="" />
Use serializeArray
data: $("form").serializeArray(),
Hope this will help.
The problem is that "data: {header: JSON.stringify(data)}" is not the same object as you expect on the controller.
This should work.
$.ajax({
type: "POST",
url: "#Url.Action("ScheduleVisit", "ScheduleVisit")",
data: data,
...
The controller expects an object like:
{
"ScheduledVisit":"08/02/2017 12:00 AM",
"Company":"fdsa",
"ContactPerson":"asfd",
"Phone":"asdf",
"Purpose":"fasd",
"Detail":"asdf"
}
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"
});
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
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; }
}
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.