Posting a complex object through ajax along with other simple types - ajax

I know that this question has been asked like a hundred times, but I can't figure it out.
I have an ajax call like
function saveBox()
{
var postModel = createBoxPostModel();
showLoader();
$.ajax({
async: true,
type: 'post',
url: '#(Url.BuildAction<IncomingGoodsVerificationController>(x => x.SaveWorkUnitForBox(null, null, null)))',
data: { jsonPostModel: postModel, boxItemKey: boxItemKey, itemKey: itemKey },
success: function (data, status) {
...
},
error: function (jqXHR, textStatus, errorThrown) {
hideLoader();
displayErrorMessagePopup('Error in saving box! ', errorThrown, 'error-msgs');
}
});
}
and the controller method is like
[HttpPost]
public JsonResult SaveWorkUnitForBox(NewWorkUnitBoxModel postModel, string boxItemKey, string itemKey)
{
....
}
The NewWorkUnitBoxModel is
public class NewWorkUnitBoxModel
{
public NewWorkUnitBoxModel();
public string AlternativeWorkUnitNumer { get; set; }
public string Barcode { get; set; }
public int ChooseType { get; set; }
public decimal? GrossWeight { get; set; }
public long IdCompany { get; set; }
public long? IdPackagingType { get; set; }
public long? IdWorkUnitSubType { get; set; }
public decimal? NetWeight { get; set; }
public string Tone { get; set; }
public decimal? Volume { get; set; }
public long? WorkUnitNumber2 { get; set; }
}
and yet when the controller action is called is either null or the object has no value for each of its properties.
I tried several ways:
data: { jsonPostModel: postModel, boxItemKey: boxItemKey, itemKey: itemKey }
data: { jsonPostModel: JSON.stringify(postModel), boxItemKey: boxItemKey, itemKey: itemKey }
Putting all action parameters inside a request class
None of these worked. Client-side the model is loaded correctly, and by using ModelBinders I also looked inside the HtmlRequest and data had arrived on the server. I only solved with changing the type to a string and deserialize it inside the action.
How can I make it automatically deserialize the model?

Related

How to convert formcollection to model ins ASP.NET MVC

I have a model class called ClientPackage and in my controller action method i receive a FormCollection from an ajax post call that i would like to convert it to the model class ClientPackage.
public class ClientPackage
{
public int DemandeId { get; set; }
public string NumeroRequette { get; set; }
public string NumeroModification { get; set; }
public int CasId { get; set; }
public string NumeroDossier { get; set; }
public string NomPatient { get; set; }
public string PrenomPatient { get; set; }
public string NiveauPriorite { get; set; }
public int NiveauPrioriteId { get; set; }
public Unite UniteDepart { get; set; }
public Unite UniteDestination { get; set; }
public Demandeur DemandeurDepart { get; set; }
public Demandeur DemandeurDestination { get; set; }
public ConditionTransport ConditionTransport { get; set; }
public Transport Transport { get; set; }
}
[HttpPost]
public string AjaxCall(FormCollection formData)
{
ClientPackage package = (ClientPackage)formData; //exception error
}
I would appriciate any help
Instead of trying to convert you can use the FromForm attribute and receive your model as a parameter.
[HttpPost]
public ActionResult CreateClientPackage([FromForm] ClientPackage clientPackage)
{
...
}
Here is how I post models with ajax.
<script>
function PostForm() {
var model = $('#your_form_id').serialize();
$.ajax({
url: '/YourController/AjaxCall',
type: 'POST',
data: model,
success: function (data) {
},
error: function (request, error) {
console.log("Request: " + JSON.stringify(request));
}
});
}
</script>
and in your controller.
[HttpPost]
public string AjaxCall(ClientPackage model)
{
//no need to cast the model to a ClientPackage
//ASP.NET mvc will do it for you as long as you send a serialized form that represents a ClientPackage object
}
Hope this helps!

Unable to pass data from jQuery.ajax to .net Core 2.1 Actionresult

I want to send data to a .net core 2.1 Action method. I collect the data with jQuery and send it with Ajax. When inspecting the payload the object I want to send is there. But the method wont recivie it. All the values are Null.
The Code:
C#
public class Customer
{
public int CustomerID { get; set; }
public string Name { get; set; }
public string OrgNumber { get; set; }
public string AdressLine1 { get; set; }
public string AdressLine2 { get; set; }
public string ZipCode { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string Image { get; set; }
public int? StatusID { get; set; }
}
[HttpPost]
public async Task<IActionResult> Edit(Customer customer)
{
}
return View();
JavaScript
var customerObject = {
CustomerID: customerID,
Name: customerName,
OrgNumber: orgNumber,
AdressLine1: adressOne,
AdressLine2: adressTwo,
ZipCode: zipCode,
City: City,
Country: Country,
Image: customerImage,
StatusID: statusId
}
var url = `#Url.Action("Edit")`;
var postData = $.ajax({
url: url,
dataType: "json",
contentType: "application/json;",
data: { data: JSON.stringify(customerObject) },
method: 'POST',
async: true,
crossDomain: true
});
Payload from browser
data=%7B%22CustomerID%22%3A%2211%22%2C%22Name%22%3A%22Bambino+Kran%22%2C%22OrgNumber%22%3A%22456456131%22%2C%22AdressLine1%22%3A%22Lustikullagatan66%22%2C%22AdressLine2%22%3A%22%22%2C%22ZipCode%22%3A%2216578%22%2C%22City%22%3A%22H%C3%A4sselby%22%2C%22Country%22%3A%22%C3%96zbeckistan%22%2C%22Image%22%3A%22%22%2C%22StatusID%22%3A%221%22%7D
Payload deserialized:
{"CustomerID":"11","Name":"Bambino Kran","OrgNumber":"456456131","AdressLine1":"Lustikullagatan66","AdressLine2":"","ZipCode":"16578","City":"Hässelby","Country":"Özbeckistan","Image":"","StatusID":"1"}
Found this with a little bit of searching and solved it:
jObject

500 error in Ajax Get

I'm trying to send a dropdownlists selected value to controller and retrieve json data back.
When I debug, parameter gets to controller nicely, values are retrieved nicely but after return part on console it says
"Failed to load resource: the server responded with a status of 500 (Internal Server Error)`"
This is my controller action: (in WebContentsController)
[HttpGet]
public JsonResult GetWebContentTypeDetails (int id)
{
var details = db.WebContentTypeDetail.Where(x=>x.WebContentTypeID == id).ToList();
return Json(details, JsonRequestBehavior.AllowGet);
}
this is JS part (printing it to console for testing)
$(document).ready(function () {
$("#WebContentTypeID").change(function () {
var ChangedID = $('#WebContentTypeID option:selected').val();
alert(ChangedID);
$.getJSON('/webcontents/GetWebContentTypeDetails/' + ChangedID, function (data) {
console.log(data);
})
});
});
EDIT:
WebContentTypeDetail model
public partial class WebContentTypeDetail
{
public int WebContentTypeDetailID { get; set; }
public int WebContentTypeID { get; set; }
public string DetailKey { get; set; }
public string Description { get; set; }
public Nullable<short> Rank { get; set; }
public virtual WebContentType WebContentType { get; set; }
}
WebContentType model
public partial class WebContentType
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public WebContentType()
{
this.WebContent = new HashSet<WebContent>();
this.WebContentTypeDetail = new HashSet<WebContentTypeDetail>();
}
public int WebContentTypeID { get; set; }
public string DisplayName { get; set; }
public string CreatedByUserID { get; set; }
public System.DateTime CreateDate { get; set; }
public string LastEditedByUserID { get; set; }
public Nullable<System.DateTime> LastEditDate { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<WebContent> WebContent { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<WebContentTypeDetail> WebContentTypeDetail { get; set; }
}
You cannot directly return a entity list from context query result, because they are not serializable in most of cases, especially in your case: entities got a loop references.
you have 2 options:
var details = db.WebContentTypeDetail.Where(x=>x.WebContentTypeID == id)
map your result to anonymous object list:
return Json(details.select(x=>new {
//you data structure
}).ToList(), JsonRequestBehavior.AllowGet);
create your view model and mark it [Serializable], then return necessary data to client:
return Json(details.select(x=>new YourViewModel {
//you data structure
}).ToList(), JsonRequestBehavior.AllowGet);
Try this:
$(document).ready(function () {
$("#WebContentTypeID").change(function () {
var ChangedID = $('#WebContentTypeID option:selected').val();
alert(ChangedID);
$.getJSON('/webcontents/GetWebContentTypeDetails?id=' + ChangedID, function (data) {
console.log(data);
})
});
});
As parameter id should be passed as querystring. And if you're using mvc then url should be passed in #url.action so it must be
$(document).ready(function () {
$("#WebContentTypeID").change(function () {
var ChangedID = $('#WebContentTypeID option:selected').val();
alert(ChangedID);
var URL = #Url.Action("_GetWebContentTypeDetails", "webcontents");
$.getJSON(URL + '?id=' + ChangedID, function (data) {
console.log(data);
})
});
});

How to pass IEnumerable model to controller

My model is
public class InvBrojeviModel
{
public int rb { get; set; }
public int id_ulaz_sredstava { get; set; }
public int? inv_broj { get; set; }
public string serijski_broj { get; set; }
public int id_sifra { get; set; }
}
I'm trying to pass this model to controller with an ajax call
var m = '#Html.Raw(Json.Encode(Model))';
$.ajax({
url: "/Ulazna_Dokumenta/InvBrojevi_Post",
type: 'POST',
data: JSON.stringify(m),
dataType: 'json',
success: function (data) {
alert("OK");
}
});
I can see the model is serialized. Serialized structure is
"[{\"rb\":6477,\"id_ulaz_sredstava\":308,\"inv_broj\":6477,\"serijski_broj\":null,\"id_sifra\":29},{\"rb\":6478,\"id_ulaz_sredstava\":308,\"inv_broj\":6478,\"serijski_broj\":null,\"id_sifra\":29},{\"rb\":6479,\"id_ulaz_sredstava\":308,\"inv_broj\":6479,\"serijski_broj\":null,\"id_sifra\":29},{\"rb\":6480,\"id_ulaz_sredstava\":308,\"inv_broj\":6480,\"serijski_broj\":null,\"id_sifra\":29}]":
But in controller the input parameter is NULL. The controller is
[HttpPost]
public ActionResult InvBrojevi_Post(IEnumerable<Magacin.Models.InvBrojeviModel> _invBrojeviModel)
{
return Json("test");
}
The input parameter _invBrojeviModel is NULL. Why?

Post a Javascript array not working with DefaultModelBinder?

Code
I can not send an array of javascript objects to the server.
ModelBinder standard does not recognize the format.
On my server I have classes:
public class PessoaViewModel
{
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
public string Nome { get; set; }
public string Tipo { get; set; }
public string CPF { get; set; }
public ICollection<TelefoneViewModel> Telefones { get; set; }
public ICollection<EnderecoViewModel> Enderecos { get; set; }
public ICollection<EmailViewModel> Emails { get; set; }
public PessoaViewModel Conjuge { get; set; }
}
public class TelefoneViewModel
{
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
[AdditionalMetadata("class", "span2")]
[AdditionalMetadata("placeholder", "Tipo")]
public string Tipo { get; set; }
[DataType(DataType.PhoneNumber)]
[AdditionalMetadata("class", "span2")]
public string Numero { get; set; }
[HiddenInput(DisplayValue = false)]
public int Ordem { get; set; }
}
I'm not listing the rest of the class because it is not yet used in the code!
My javascript
$.ajax
url: $(form).attr("action")
type: "POST"
error: (err, errType, errMessage) ->
console.error a.statusText
cache: false
data: ko.mapping.toJS(#, ignoreFunctionsMapping)
success: (data, txtStatus) -> console.log "OK!!?? On server maybe not!"
Server result
Full image: http://i.stack.imgur.com/NeIm1.jpg
Question
As you can see, the post is being done and the values ​​are correct.
But asp.net mvc does not fill correctly the Telefones object!
What am I doing wrong?
Your problem is because you are missing a ".", it should have the format:
Telefones[0].Id: 1
Telefones[0].Ordem: bli

Resources