How to pass an array in formData - javascript

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:

Related

I want to save data in two different tables with linq and ajax post

I want to save data in two different tables with linq and ajax post, and if you can help me about the way I should follow when I send it to the controller, I would be very grateful to everyone. I do
public class Student
{
public int StudentID { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
}
public class StudentDetail
{
public int StudentDetailID { get; set; }
public int StudentID { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public string Number { get; set; }
}

Reading Javascript FormData value in Asp.net Web api Httpresponsemessage

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);
...
}

mvc controller is passing in null from javascript object that has data

I have an MVC controller that somehow is passing in Null to it
Controller:
[HttpPost]
public ActionResult UpdateAllNodes(IEnumerable<ReportGroup> reportGroups)
{
// this is custom return..
return JsonCamel(null);
}
PROBLEM : reportGroups is null
javascript ajax post
$.post(updateAllNodeUri, JSON.stringify({ reportGroups: homogeneous.data() }));
Chrome Dev Tools Form Data:
{"reportGroups":[
{"Id":1,"ReportGroupName":"Standard Reports","ReportGroupNameResID":null,"SortOrder":1,"items":[],"index":0},
{"Id":2,"ReportGroupName":"Custom Reports","ReportGroupNameResID":null,"SortOrder":2,"items":[],"index":1},
{"Id":3,"ReportGroupName":"Retail Reports","ReportGroupNameResID":null,"SortOrder":3,"items":[],"index":2},
{"Id":4,"ReportGroupName":"Admin Reports","ReportGroupNameResID":null,"SortOrder":5,"items":[],"index":3},
{"Id":5,"ReportGroupName":"QA Reports","ReportGroupNameResID":null,"SortOrder":4,"items":[],"index":4},
{"ReportGroupName":"Node","index":5}
]}:
So I have the reportGroups in controller along with the JSON as reportGroups: thus I'm lost on why it is null.
Also here here the poco class for the ReportGroup
public class ReportGroup : BaseEntity
{
public override int Id { get; set; }
public string ReportGroupName { get; set; }
public int? ReportGroupNameResID { get; set; }
public int SortOrder { get; set; }
}
Kendo data calls , then I can output to console and see the data as well
console.log(homogeneous.data());
// ### Send the Data to the server
var updateAllNodeUri = "/Report/UpdateAllNodes";
Based on the JSON data you get from Chrome Dev Tools, you are actually sending the JSON with this model:
JSON:
{"reportGroups":[
{"Id":1,"ReportGroupName":"Standard Reports","ReportGroupNameResID":null,"SortOrder":1,"items":[],"index":0},
{"Id":2,"ReportGroupName":"Custom Reports","ReportGroupNameResID":null,"SortOrder":2,"items":[],"index":1},
{"Id":3,"ReportGroupName":"Retail Reports","ReportGroupNameResID":null,"SortOrder":3,"items":[],"index":2},
{"Id":4,"ReportGroupName":"Admin Reports","ReportGroupNameResID":null,"SortOrder":5,"items":[],"index":3},
{"Id":5,"ReportGroupName":"QA Reports","ReportGroupNameResID":null,"SortOrder":4,"items":[],"index":4},
{"ReportGroupName":"Node","index":5}
]}:
Model:
public class ReportGroup
{
public int Id { get; set; }
public string ReportGroupName { get; set; }
public object ReportGroupNameResID { get; set; }
public int SortOrder { get; set; }
public List<object> items { get; set; }
public int index { get; set; }
}
public class RootObject
{
public List<ReportGroup> reportGroups { get; set; }
}
The RootObject class is the one being received by your controller which is not the expected parameter.
Try transforming the JSON to this format:
[
{"Id":1,"ReportGroupName":"Standard Reports","ReportGroupNameResID":null,"SortOrder":1,"items":[],"index":0},
{"Id":2,"ReportGroupName":"Custom Reports","ReportGroupNameResID":null,"SortOrder":2,"items":[],"index":1},
{"Id":3,"ReportGroupName":"Retail Reports","ReportGroupNameResID":null,"SortOrder":3,"items":[],"index":2},
{"Id":4,"ReportGroupName":"Admin Reports","ReportGroupNameResID":null,"SortOrder":5,"items":[],"index":3},
{"Id":5,"ReportGroupName":"QA Reports","ReportGroupNameResID":null,"SortOrder":4,"items":[],"index":4},
{"ReportGroupName":"Node","index":5}
]
Javascript:
$.post(updateAllNodeUri, JSON.stringify(homogeneous.data()));

Infragistics IgniteUI Tree Load OnDemand

I am using the plugin http://www.igniteui.com/tree/overview and want to load the tree data on demand.
My declaration of the tree is :
$("#tree").igTree({
checkboxMode: "off",
singleBranchExpand: true,
loadOnDemand: true,
dataSourceUrl : "/home/getagreements",
nodeClick: function (evt, ui) {
},
dataSourceType: "json",
initialExpandDepth: -1,
pathSeparator: ".",
bindings: {
textKey: "Text",
valueKey: "Value",
imageUrlKey: "ImageUrl",
childDataProperty: "Value",
Description: "Description"
},
},
dragAndDrop: false,
nodeExpanding: function (evt, ui) {
}
});
and the JSON output for home/getagreements is
return Json(agrmnts, JsonRequestBehavior.AllowGet);
where
List<Agreements> agrmnts = new List<Agreements>();
and the class definitions as below:
[JsonObject(MemberSerialization = Newtonsoft.Json.MemberSerialization.OptIn)]
public class AgreementNode
{
[JsonProperty(Order = 1)]
public string AgreementNbr { get; set; }
[JsonProperty(Order = 2)]
public string ExternalDescription { get; set; }
[JsonProperty(Order = 3)]
public string Description { get; set; }
[JsonProperty(Order = 4)]
public string EffDate { get; set; }
[JsonProperty(Order = 5)]
public string ExpDate { get; set; }
[JsonProperty(Order = 6)]
public string ReleaseStatus { get; set; }
[JsonProperty(Order = 7)]
public string ImageUrl { get; set; }
[JsonProperty(Order = 8)]
public string Folder { get; set; }
[JsonProperty(Order = 9)]
public string Value { get; set; }
[JsonProperty(Order = 10)]
public string Text { get; set; }
}
public class Agreements
{
public string AgreementType { get; set; }
public string Text { get; set; }
public string Value { get; set; }
public string Folder { get; set; }
public string ImageUrl { get; set; }
public List<AgreementNode> agreements { get; set; }
}
The first level data is displayed correct but when I click the node the same data is binding again. Please suggest if I am missing any configuration settings for Loading on Demand
With the current configuration the igTree is using the dataSourceUrl to request the new data from the same controller action you used to bind the initial level. At this point you would need to use the parameters the tree is providing to the controller action - path, binding and depth - to return the correct layer of data.
Here's an example of how you can do this.

Insert "Multiple Field Value" in the Same Column in MVC4?

I want to save the Multiple field Values in the same Column.
TaxField Table contain 3 Fields
1)TaxFieldID
2)DisplayName
3)PrintName
TaxFieldID = FD713788-B5AE-49FF-8B2C-F311B9CB0CC4
DisplayName = TinNo
PrintName = TinNo
The value of TinNo CinNo etc all are have default value which is saved in TaxField Table
TaxInfoTaxField Table
My View contain six fields TinNo, CstNo, PanNo, ServiceTaxNo,ExciseRegNo, CinNo.
Format to save the Value and ID in TaxInfoTaxFieldTable
TinNo = FD713788-B5AE-49FF-8B2C-F311B9CB0CC4
CstNo = 64B512E7-46AE-4989-A049-A446118099C4
CinNo =59A2449A-C5C6-45B5-AA00-F535D83AD48B
My Model
public partial class TaxInfoTaxFiled
{
public System.Guid TaxInfoTaxFieldID { get; set; }
public Nullable TaxInfoID { get; set; }
public Nullable TaxFieldID { get; set; }
public Nullable FieldTypeID { get; set; }
public string FieldValue { get; set; }
}
public partial class TaxField
{
public System.Guid TaxFieldID { get; set; }
public string DisplayName { get; set; }
public string PrintName { get; set; }
}
MyViewModel
public class TaxViewModel1
{
public System.Guid TaxInfoTaxFieldID { get; set; }
public System.Guid TaxInfoID { get; set; }
public Nullable TaxFiledID { get; set; }
public string TinNo { get; set; }
public string CstNo { get; set; }
public string ExciseRegNo { get; set; }
public string PanNo { get; set; }
public string ServiceTaxNo { get; set; }
public string CinNo { get; set; }
}
public class VisitorsEntities1 : DbContext
{
public DbSet TaxField { get; set; }
public DbSet TaxInfo { get; set; }
public DbSet TaxInfoTaxFiled { get; set; }
}
My Controller
[HttpPost]
public ActionResult Index(TaxViewModel1 TVM)
{
Type type = typeof(TaxField);
PropertyInfo[] Info = new
TaxInfoTaxField().GetType().GetProperties();
foreach (TaxInfoTaxField property in properties)
{
var Value = property.GetValue(TVM.TinNo, null);
var Value1 = property.GetValue(TVM.CstNo, null);
}
return View(Tax);
}
Sir In this below Code we pass the Properties of TaxField and it is get by TaxinfoTaxField Table
Type type = typeof(TaxField);
PropertyInfo[] Info = new TaxInfoTaxField().GetType().GetProperties();
And in 'foreach Loop ' we assigning the Value to the Variable. But how to assign the value to the Column .And How to do save the Value in FieldValue and ID in TaxFieldID of TaxInfoTaxField Table in the above format which I mentioned. Please Correct my Controller Code . I am very very new to MVC . so only I struggling for this Small Concepts. Please correct my Controller Code and help me to save the Values in the TaxInfoTaxField table. And if you have a times means please explain me the Logic used in Controller.
Thanks.

Categories