I have a Web api which is decorated with [HttpPost] which is used to upload all information passed in parameter but getting this error
Error
Controller
[HttpPost]
public HttpResponseMessage questionnairesubmit(HttpRequestMessage form)
{
//want to get json of "questionlist" which is send from javascript like
var QuestionnaireList = JsonConvert.DeserializeObject<List<outRightLogos.Areas.client.WebApiModel.AttributeValueTB>>(form["questionlist"]);
}
Here is javascript sending Json model with name questionlist this I want to fetch in controller.I read FormData() from Here
Javascript
var data = new FormData();
var QuestionnaireList = [];
QuestionnaireList.push({
FieldID: $(this).attr("data-fieldid"),
attributeID: $(this).attr("data-attributeid"),
attributeValue: $(this).val(),
websitesID: 2,
OrderID: $('#orderid').val(),
orderbitID: $('#orderbidid').val(),
serviceId: $(this).attr("data-serviceid"),
subServiceId: $(this).attr("data-subserviceid"),
IsSubmit: IsSubmit,
});
data.append("questionlist", JSON.stringify(QuestionnaireList));
$.ajax({
type: "POST",
url: path,
contentType: 'application/json',//"application/json; charset=utf-8",
processData: false,
dataType: "json",
data: data,
success: function (result) {
if (result.sucess == "save") {
alert('Your form has been saved.');
}
else if (result.sucess == "Submit") {
alert('Your form has been submitted.');
window.location.href = result.Url;
}
},
error: function (result) {
alert('Oh no ');
}
});
Here is a model class AttributeValueTB
Class
public class AttributeValueTB
{
public long attributeValueID { get; set; }
[Required]
[StringLength(200)]
public string attributeValueCode { get; set; }
public int FieldID { get; set; }
public int attributeID { get; set; }
public string attributeValue { get; set; }
public int websitesID { get; set; }
public long OrderID { get; set; }
public long orderbitID { get; set; }
public long serviceId { get; set; }
public long subServiceId { get; set; }
public string extra1 { get; set; }
public string extra2 { get; set; }
[StringLength(200)]
public string attributeCode { get; set; }
public bool isActive { get; set; }
public bool isShow { get; set; }
public bool IsSubmit { get; set; }
[Column(TypeName = "date")]
public DateTime? createDate { get; set; }
[Column(TypeName = "date")]
public DateTime? modifiedDate { get; set; }
public int? createBy { get; set; }
public int? modifiedBy { get; set; }
[Column(TypeName = "timestamp")]
[MaxLength(8)]
[Timestamp]
public byte[] Timestamp { get; set; }
}
You don't need to serialize anything manually, as long as you've provided a model class in C#.
Json.NET is quite smart and serializes your parameters automagically.
[HttpPost]
public HttpResponseMessage QuestionnaireSubmit(AttributeValueTB form)
{
// Form is serialized and can be used here
}
If you'd like to read the cookies too, you could use Request.Cookies in this method.
you need to collect information from 'jsoncontent' not from 'form'
HttpContent requestContent = Request.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;
entityclass obj= JsonConvert.DeserializeObject<entityclass>(jsonContent);
and if you using class object as parameter also work with your context, need to change the method as put like this.
[HttpPut]
public HttpResponseMessage Put(int id)
{
HttpContent requestContent = Request.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;
entityclass obj= JsonConvert.DeserializeObject<entityclass>(jsonContent);
...
}
Related
Im trying to pass an Id and object of picList to the controller and it shows up null. I've looked at all the other SO solutions and changed my code to what they said and Im still getting null for both values in the controller.
So I've even tried to change the data that is being sent to the controller as such to see if that made any difference and it didn't.
in ajax call i changed the data to such
data: {"Name": "Adam"},
and added this to the controller and still nothing is getting passed.
UnitImages(string Name,..
here is what the JSON.stringify(data) looks like.
View Model
public class FileViewModel
{
public FileViewModel()
{
UnitPicturesList = new List<UnitPictures>();
}
public IList<IFormFile> Files { get; set; }
[Required]
public int AuctionId { get; set; }
public string FileLocation { get; set; }
public List<UnitPictures> UnitPicturesList { get; set; }
}
model
public class UnitPictures
{
public long ImageId { get; set; }
public string FileName { get; set; }
public string FileLocation { get; set; }
public int SortOrder { get; set; }
}
controller
[HttpPost]
public ActionResult UnitImages(long auctionId, List<UnitPictures> picList)
{ ...
}
Ajax call
function UpdateImages(auctionId, picList) {
var data = { auctionId: auctionId, picList: picList };
console.log(JSON.stringify(data));
$.ajax({
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
url: '/PhotoUploader/UnitImages',
data: JSON.stringify(data),
success: function(data){
if(data.Result == 1) {
alert("images where successfully updated.");
}else {
alert('images where successfully updated.');
}
},
error: function() {
alert("The images were not updated because of a problem.")
}
});
}
Asp.net core MVC default binding value from form, Here you can try to add [FromBody] attribute on your parameter to change the resource to bind value from body.
[HttpPost]
public ActionResult UnitImages([FromBody]string Name)
{ ...
}
Model details you can refer to Model Binding.
Try using a class that match the posted model. Something like this:
public class UnitPictures_ViewModel
{
public int AuctionId {get;set;}
public List<UnitPictures> PicList { get; set; }
}
public class UnitPictures
{
public long ImageId { get; set; }
public string FileName { get; set; }
public string FileLocation { get; set; }
public int SortOrder { get; set; }
}
I am trying to pass a list of objects to Controller using ajax, it works and shows how many items are there but shows items as null and I do not know what I am misisng.
I have this in JavaScript:
var data = {
"expediente": '#Model.NUMEMP',
"edad": '#edad',
"sexo": '#Model.SEXO',
"piezasConNotas": piezasYNotas,
//"servicio": $("#actividades").val(),
//"subServicio": $("#actividadesRealizar").val(),
"diagnostico": $("#diagnosticos").val(),
"interconsulta_esp": "",
"interconsulta": $("#interconsulta").val(),
};
console.log(data);
$.ajax({
'url': ' #Url.Action("AgregarExpedienteDental", "ServiciosMedicos")',
"data": data ,
"success": function (result) {
if (result === "1") {
//swal("Good job!", "You clicked the button!", "success");
Swal.fire('Success', 'Se ha insertado', 'success');
setTimeout('', 3000);
const myTimeout = setTimeout(myGreeting, 1500);
}
},
"error": function (response) {
}
});
this is what console.log(data) shows:
and when I send them to controller this is how it shows in the debugger:
as you can see other data is ok and the count from the list is ok but the items are going inside
as null.
I do not know what I am doing wrong? How do I solve this?
this is my C# code:
public JsonResult AgregarExpedienteDental(ExpedienteDentall data)
{
....
}
public class ExpedienteDentall
{
public string diagnostico { get; set; }
public string edad { get; set; }
public string expediente { get; set; }
public string interconsulta { get; set; }
public string interconsulta_esp { get; set; }
//public string servicio { get; set; } = "";
public string sexo { get; set; }
//public string subServicio { get; set; } = "";
public List<piezasConNotas> piezasConNotas { get; set; }
}
public class piezasConNotas
{
public string diente { get; set; }
public string nota { get; set; }
public string actividad { get; set; }
public string actividadRealizada { get; set; }
}
I am using formData and trying to pass an array that receives it in .Net Core backend
this is my array that i try to send truck.StateTruck:
{
0: {StaId: 6}
1: {StaId: 7}
2: {StaId: 8}
3: {StaId: 9}
}
this is my method to send my data that I try to send only the StaId and its value:
let formData = new FormData();
formData.set('DriId',truck.DriId);
formData.set('TruExdate',truck.TruExdate);
formData.set('TruAddress',truck.TruAddress);
formData.set('TruCity',truck.TruCity);
formData.set('TraId',truck.TraId);
formData.set('TruZip',truck.TruZip);
formData.set('TruYear',truck.TruYear);
formData.set('TruMake',truck.TruMake);
formData.set('TruType',truck.TruType);
formData.set('TruFuel',truck.TruFuel);
formData.set('TruAxles',truck.TruAxles);
formData.set('TruVin',truck.TruVin);
formData.set('TruDocurl',truck.TruDocurl);
formData.set('TraUnit',truck.TraUnit);
formData.set('TraMake',truck.TraMake);
formData.set('TraYear',truck.TraYear);
formData.set('TtyId',truck.TtyId);
formData.set('TraIntmaterial',truck.TraIntmaterial);
formData.set('TraEquipament',truck.TraEquipament);
formData.set('TraOption',truck.TraOption);
formData.set('Fichero',truck.Fichero);
formData.append('StateTruck',JSON.stringify(truck.StateTruck));
when printing to the console using the console.log (formData.getAll ('StateTruck')); I see
["[{"StaId":6},{"StaId":7},{"StaId":8},{"StaId":9}]"]
and my backend expects this structure:
public class TruckRequest
{
public int TruId { get; set; }
public int? DriId { get; set; }
public DateTime? TruExdate { get; set; }
public string TruAddress { get; set; }
public string TruCity { get; set; }
public int? TraId { get; set; }
public string TruZip { get; set; }
public string TruYear { get; set; }
public string TruMake { get; set; }
public string TruType { get; set; }
public string TruFuel { get; set; }
public string TruAxles { get; set; }
public string TruVin { get; set; }
public string TruDocurl { get; set; }
public string TraUnit { get; set; }
public string TraMake { get; set; }
public string TraYear { get; set; }
public int? TtyId { get; set; }
public string TraIntmaterial { get; set; }
public string TraEquipament { get; set; }
public string TraOption { get; set; }
public IFormFile Fichero { get; set; }
public string TruUregistro { get; set; }
public DateTime? TruUfecha { get; set; }
public string TruUupdate { get; set; }
public DateTime? TruUupdatefecha { get; set; }
public string TruEstado { get; set; }
public virtual ICollection<StateTruck> StateTruck { get; set; }
}
public partial class StateTruck
{
public int SruId { get; set; }
public int? StaId { get; set; }
public string SruUregistro { get; set; }
public DateTime? SruUfecha { get; set; }
public string SruUupdate { get; set; }
public DateTime? SruUupdatefecha { get; set; }
public string SruEstado { get; set; }
public int? TruId { get; set; }
}
How can I give it the correct format so that it can be received?
if you need the value converted to string, you may use
e.g.
formData.set('TruYear', truck.TruYear.toString());
for integer, e.g.
formData.set('TruYear', parseInt(truck.TruYear));
All these are passed as formData to your backend, your server should create the parser to convert to the right format, and to validate it is the right format.
Never, trust, anything submitted from frontend.
When console logging out the data you need to parse the first element in the array received from formData.getAll ('StateTruck'). The following should help in your scenario:
console.log(JSON.parse(formData.getAll("StateTruck")[0]))
According to your description, I assume you want to use FormData to pass value (include the object array) from client side to server side (Web API). If that is the case, you could refer to the following sample code:
Client side (using JQuery Ajax to call the web API method):
$(function () {
//Submit Main Form.
$("#btnCreate").click(function (event) {
//Prevent Default Region.
event.preventDefault();
//define an array to store the StateTruck
var statetruce = new Array();
for (var i = 0; i < 5; i++) {
statetruce.push({ StaId: i });
}
let formData = new FormData();
formData.set('DriId', 101);
formData.set('TruAddress', "Address 1");
formData.set('TruCity', "city A");
formData.set('TraId', 1011);
formData.set('TruZip', "zip12");
formData.set('TruYear', "years ");
formData.append('StateTruck', JSON.stringify(statetruce));
$.ajax({
url: '/api/TestAPI',
type: "post",
async: true,
data: formData,
processData: false,
contentType: false,
success: function (response) {
// window.location.href = response;
}
});
});
});
Based on the Array Object's property to create a View Model, it is used to Deserialize the array object.
Code in the Web API method:
[HttpPost]
public async Task<IActionResult> Post(IFormCollection collection)
{
var DriId = collection["DriId"].ToString();
var TruAddress = collection["TruAddress"].ToString();
var StateTruck = collection["StateTruck"].ToString();
//deserialize the object
var result = System.Text.Json.JsonSerializer.Deserialize<List<StateTruckViewModel>>(StateTruck);
//do something
return Ok("success");
}
Then debug screenshot as below:
I have some problem while getting the object from the controller via AJAX call.To be precise, I would like to get the object which contains property with IEnumerable type.
Class 1 :
public class ChartItem
{
public string cName { get; set; }
public string label { get; set; }
public decimal value { get; set; }
public decimal value2 { get; set; }
public string value2Cur { get; set; }
public string value2Unit { get; set; }
public string color { get; set; }
public string strokeColor { get; set; }
public string chartTitle { get; set; }
}
Class 2 :
public class ReportParameter
{
public string ReportName { get; set; }
public string DateFrom { get; set; }
public string DateTo { get; set; }
public string CountryId { get; set; }
public string RegionId { get; set; }
public string RepresentativeId { get; set; }
public string CustomerId { get; set; }
public ExportFormatType ReportFormat { get; set; }
public EReport.ChartType ChartType { get; set; }
public bool EmailFlag { get; set; }
public IEnumerable<ChartItem> chartItems { get; set; }
}
This is the controller that execute the call :
[HttpPost]
public JsonResult ReloadReportSummary(EReport.ReportParameter rptParam)
{
EMAP.WEB_Bootstrap.Helper.ViewHelper viewHelper = new ViewHelper();
IEnumerable<EReport.ChartItem> resultChart=null;
try
{
EReport.ReportParameter eRpt = new EReport.ReportParameter();
eRpt.ReportName = ((EReport.ReportName)Enum.Parse(typeof(EReport.ReportName), rptParam.ReportName)).ToString();
switch ((EReport.ReportName)Enum.Parse(typeof(EReport.ReportName), rptParam.ReportName))
{
case EReport.ReportName.CRPotentialCustomerList:
//reload the chart data
resultChart =
from cp in db.CustomerProducts
join pr in db.Products on cp.ProductID equals pr.ProductID
group cp by cp.Product.ProductDescription into grp
select new EReport.ChartItem { label = grp.Key, value = grp.Count()};
break;
case EReport.ReportName.CRCustomerProductAppMasterPivot:
//reload the chart data
resultChart =
from cp in db.CustomerProducts
join pr in db.Products on cp.ProductID equals pr.ProductID
group cp by cp.Product.ProductDescription into grp
select new EReport.ChartItem { label = grp.Key, value = grp.Count() };
break;
default:
break;
}
eRpt.chartItems = resultChart;
---EDITED----
var result = eRpt;
return Json(new { Result = "OK", Record = result },
JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { Result = "ERROR"});
}
}
And this is the AJAX call :
$.ajax({
url: urlReportSummary,
data: JSON.stringify(rptParam),
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
success: function (result) {
var len = result.Record.chartItem.length;
},
error: function (ex) {
alert(ex);
}
});
Actually I would like to go through each Record.chartItem's object and do some process there. But somehow the returned record not being recognized. Below is the error :
"TypeError: result.Record.chartItem is undefined".
May I know what is the correct way to get the list of data using AJAX ?
Thanks a lot
Change the success function as below and try
success: function (result) {
var len = result.Record.chartItems.length;
},
You have misspelled the property chartItems. I think now it will work
Not sure if it's just the time of day, lack of coffee or over indulgence of sugar from last night. Besides that I'm trying to get this working. I do not want to change / modify / add a new web service method.
I have an asmx web service:
public UserLogin Login(UserLogin p_objUserLogin)
{
}
I need to hook a JQuery ajax call up to that. The UserLogin object is not that complex:
public class UserLogin
{
public UserLogin();
public string Privileges { get; set; }
public string ClientCodeID { get; set; }
public UserDetails User { get; set; }
public string UserLoginMessage { get; set; }
public bool Valid { get; set; }
}
The UserDetails object is quite large, and includes a lot more data. (Hopefully I don't need to build the entire object tree to get this to work).
public class UserDetails
{
public string CellPhone { get; set; }
public string Email { get; set; }
public string EncryptedPassword { get; set; }
public string FirstName { get; set; }
public string FullName { get; }
public string Initials { get; set;
public bool InService { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public byte[] Signature { get; set; }
public string SimCard { get; set; }
public int UserID { get; set; }
public string UserName { get; set; }
public SecurityRole UserSecurityRole { get; set; }
public Workgroup UserWorkgroup { get; set; }
}
The script I'm playing around with:
function CallService() {
var p_objUserLogin = {};
p_objUserLogin['ClientCodeID'] = "Test";
var DTO = { 'p_objUserLogin': p_objUserLogin };
$.ajax({
type: "POST",
url: "UtilityServices2006.asmx/Login",
data: JSON.stringify(DTO),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (msg) {
alert(msg);
},
error: function (req, status, error) {
alert(req + ", " + status + ", " + error);
},
complete: function (req, status) {
alert(req + ", " + status);
}
});
}
Any help would be quite amazing.
Ensure your webservice class and method are decorated to handle incoming ajax/json requests:
[ScriptService]
public class MyService: WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public UserLogin Login(UserLogin p_objUserLogin)
{
}
}
I'm not familiar with the notation you're using to configure your payload object (p_objUserLogin['ClientCodeID'] = "Test";). I've usually used slightly different notation:
p_objUserLogin.ClientCodeID = 'Test';
However, that might be a red herring - I'm not a JS-objects expert, so your notation may be perfectly valid.
Finally, I'm not sure if JS will automatically convert your object to JSON (var DTO = { 'p_objUserLogin': p_objUserLogin };). I use the json2 library to explicitly serialize JS objects to JSON:
var DTO = { 'p_objUserLogin': JSON.stringify(p_objUserLogin) };
Hope this helps you nail down the issue.