Always getting null value when send object with fromData other value from React - reactjs

I have send a formData from react app with some value and image files and i also want to send a obj with same formData on .net core api
Here is my class
[Bind]
public class ServiceInfo
{
public int id { get; set; }
[NotMapped]
public IFormFile[] ImgFile { get; set; }
[NotMapped]
public IFormFile ImgFilen { get; set; }
//public int { get; set; }
public string title { get; set; }
public string serImg1 { get; set; }
public string serImg2 { get; set; }
public string serImg3 { get; set; }
public string serImg4 { get; set; }
public int serCategoryId { get; set; }
public SerCategory serCategory { get; set; }
public string time { get; set; }
public string location { get; set; }
public string serviceClose { get; set; }
public string serviceOpen { get; set; }
public int CompanyInfoId { get; set; }
public virtual CompanyInfo companyInfo { get; set; }
public string serviceDetails { get; set; }
public string offeredServices { get; set; }
public bool active { get; set; }
public bool status { get; set; }
public string extraServices { get; set; }
public string whyUs { get; set; }
}
.net core controler:
serCategory always getting null
[Route("PotService")]
[HttpPost]
public IActionResult Post([FromForm] ServiceInfo service)
{
//using (MemoryStream stream = new MemoryStream())
//{
// ImgFile.CopyToAsync(stream);
// service.Data = stream.ToArray();
//}
if (string.IsNullOrWhiteSpace(_rootPath.WebRootPath))
{
_rootPath.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "Images");
}
string uploadsFolder = Path.Combine(_rootPath.WebRootPath);
int index = 0;
foreach (var item in service.ImgFile)
{
index++;
if (item != null)
{
var uniqueFileName = service.title.ToString()+index.ToString()+ DateTime.Now.ToString("ddMMyyy") + "_" + item.FileName;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
switch (index)
{
case 1 :
service.serImg1 = uniqueFileName;
break;
case 2:
service.serImg2 = uniqueFileName;
break;
case 3:
service.serImg3 = uniqueFileName;
break;
case 4:
service.serImg4 = uniqueFileName;
break;
}
}
}
//bool result = _serManager.AddService(service);
foreach (var item in service.ImgFile)
{
if (item != null)
{
var uniqueFileName = service.title.ToString() + index.ToString() + DateTime.Now.ToString("ddMMyyy") + "_" + item.FileName;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
item.CopyTo(fileStream);
}
}
}
return Ok(true);
}
And react code :
const formData = new FormData();
formData.append("id", 0);
formData.append("CompanyInfoId", activeComId);
formData.append("title", data.title);
formData.append("time", "");
formData.append("location", data.location.value);
formData.append("serviceClose", data.serviceClose.value);
formData.append("serviceOpen", data.serviceOpen);
formData.append("serviceDetails", data.serviceDetails);
formData.append("serCategoryId", data.serType.id);
formData.append("serCategory", data.serType);
formData.append("offeredServices", data.offeredServices);
formData.append("active", false);
formData.append("status", false);
formData.append("extraServices", data.extraServices);
formData.append("whyUs", data.whyUs);
formData.append("ImgFile", data.serImg1);
formData.append("ImgFile", data.serImg2);
formData.append("ImgFile", data.serImg3);
formData.append("ImgFile", data.serImg4);
for (const [key, value] of formData.entries()) {
console.log(key, value);
}
console.log(data.serType);
const res = await fetch(serPost, {
method: "POST",
body: formData,
});

Related

ASP NET Core reading complex configuration with array and JsonConverter

I have this appsettings.json
"TopLevel": [
{
"Name": "Name",
"TopChild": {
"File": {
"URL": "SomeUrl",
"Username": "Admin",
"Password": "123"
}
},
"TopChild2": [
{
"Name": "SimpleMapper",
"Mapper": {
"Param1": "",
"Param2": "",
"Param3": ""
}
},
{
"Name": "SimpleFileConverter",
"Converter": {
"ToWhat": "",
"Writer": ""
}
}
],
"TopChild3": {
"SomeProperty3": {
"WhatIsThis": "",
"SomeProp": "",
"Password": ""
}
}
},
{
"Name": "Name",
"TopChild": {
"DB": {
"ConnectionString": "String",
"Username": "Admin",
"Password": "123"
}
},
"TopChild2": [
{
"Name": "SomeConverter",
"Converter": {
"Param1": "",
"Param2": ""
}
},
{
"Name": "SimpleFileConverter",
"Mapper": {
"Param1": "",
"Param2": "",
"Param3": ""
}
}
],
"TopChild3": {
"SomePropety4": {
"SomeProp7": "",
"Password": ""
}
}
}
]
And this is the code I wrote for a model
public class TopLevelConfigRoot
{
[JsonProperty("TopLevel")]
public List<TestObject> TopLevel { get; set; }
}
public class TestObject
{
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("TopChild")]
[JsonConverter(typeof(TopChildConverter))]
public TopChildBase TopChild { get; set; }
[JsonProperty("TopChild2")]
[JsonConverter(typeof(TopChild2Converter))]
public List<TopChild2> TopChild2 { get; set; }
[JsonProperty("TopChild3")]
[JsonConverter(typeof(TopChild3Converter))]
public TopChild3Base TopChild3 { get; set; }
}
public abstract class TopChildBase { }
public abstract class TopChild3Base { }
public class File : TopChildBase
{
[JsonProperty("URL")]
public string URL { get; set; }
[JsonProperty("Username")]
public string Username { get; set; }
[JsonProperty("Password")]
public string Password { get; set; }
}
public class DB : TopChildBase
{
[JsonProperty("ConnectionString")]
public string ConnectionString { get; set; }
[JsonProperty("Username")]
public string Username { get; set; }
[JsonProperty("Password")]
public string Password { get; set; }
}
public interface ITopChild2
{
public string Name { get; set; }
public ITopChild2Type ITopChild2Type { get; set; }
}
public class TopChild2 : ITopChild2
{
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("ITopChild2Type")]
public ITopChild2Type ITopChild2Type { get; set; }
}
public abstract class ITopChild2Type
{ }
public class Mapper : ITopChild2Type
{
[JsonProperty("Param1")]
public string Param1 { get; set; }
[JsonProperty("Param2")]
public string Param2 { get; set; }
[JsonProperty("Param3")]
public string Param3 { get; set; }
}
public class Converter : ITopChild2Type
{
[JsonProperty("Param1")]
public string Param1 { get; set; }
[JsonProperty("Param2")]
public string Param2 { get; set; }
}
public class SomeProperty3 : TopChild3Base
{
[JsonProperty("WhatIsThis")]
public string WhatIsThis { get; set; }
[JsonProperty("SomeProp")]
public string SomeProp { get; set; }
[JsonProperty("Password")]
public string Password { get; set; }
}
public class SomePropety4 : TopChild3Base
{
[JsonProperty("SomeProp7")]
public string SomeProp7 { get; set; }
[JsonProperty("Password")]
public string Password { get; set; }
}
public class TopChildConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(TopChildBase);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
if (jo.ContainsKey(nameof(File)))
{
return jo[nameof(File)].ToObject<File>();
}
else if (jo.ContainsKey(nameof(DB)))
{
return jo[nameof(DB)].ToObject<DB>();
}
return null;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
public class TopChild3Converter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(TopChild3Base);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
if (jo.ContainsKey(nameof(SomeProperty3)))
{
return jo[nameof(SomeProperty3)].ToObject<SomeProperty3>();
}
else if (jo.ContainsKey(nameof(SomePropety4)))
{
return jo[nameof(SomePropety4)].ToObject<SomePropety4>();
}
return null;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
public class TopChild2Converter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(TopChild2);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JArray ja = JArray.Load(reader);
List<TopChild2> topChild2List = new List<TopChild2>();
foreach (var item in ja)
{
JObject jObject = (JObject)item;
TopChild2 TopChild2 = null;
string name = jObject[nameof(TopChild2.Name)].ToString();
if (jObject.ContainsKey(nameof(Mapper)))
{
var root = jObject[nameof(Mapper)];
Mapper mapper = new Mapper
{
Param1 = root[nameof(Mapper.Param1)].Value<string>(),
Param2 = root[nameof(Mapper.Param2)].Value<string>(),
Param3 = root[nameof(Mapper.Param3)].Value<string>()
};
TopChild2 = new TopChild2 { Name = name, ITopChild2Type = mapper };
}
else if (jObject.ContainsKey(nameof(Converter)))
{
var root = jObject[nameof(Converter)];
Converter converter = new Converter
{
Param1 = root[nameof(Converter.Param1)].Value<string>(),
Param2 = root[nameof(Converter.Param2)].Value<string>()
};
TopChild2 = new TopChild2 { Name = name, ITopChild2Type = converter };
}
topChild2List.Add(TopChild2);
}
return topChild2List;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
And now with that model I've tried using any known implementation of config inside of controller.
The only thing I came up is inserting IConfiguration via Dependency Injection and use _config = config;
And then selected it by
var section = _config.GetSection("TopLevel");
and then used it like this
var itemArray = section.AsEnumerable();
How can I then use this itemArray to convert this to either model, or a JsonString which i will then easily serialize it with Newtonsoft
var t = JsonConvert.DeserializeObject<TopLevelConfigRoot>(jsonString);
But I haven't find a way to map this itemArray to model I provided, nor I had success with writing recursive method to actually map it to JsonString.
Converter I wrote is
public string ConvertBackToJSonString(KeyValuePair<string, string>[] itemArray)
{
var root = new JObject();
var current = root;
foreach (var item in itemArray)
{
var parts = item.Key.Split(':');
var key = parts[parts.Length - 1];
var parent = current;
for (int i = 0; i < parts.Length - 1; i++)
{
var part = parts[i];
if (!current.ContainsKey(part))
current.Add(part, new JObject());
current = (JObject)current[part];
}
if (!string.IsNullOrEmpty(item.Value))
current.Add(key, new JValue(item.Value));
else
current.Add(key, new JObject());
current = parent;
}
return JsonConvert.SerializeObject(root, Formatting.Indented);
}
But that didn't work. How should this be approached to/done?
You could bind the section to a model directly with IConfigration.Bind() method
For example,in your case :
public class BindTarget
{
public string Name { get; set; }
public SomeChildClass1 TopChild { get; set; }
public List<SomeChildClass2> TopChild2 { get; set; }
public SomeChildClass3 TopChild3 { get; set; }
}
public class SomeChildClass1
{
public File File { get; set; }
public DB DB { get; set; }
}
public class SomeChildClass2
{
public string Name { get; set; }
public Mapper Mapper { get; set; }
public Converter Converter { get; set; }
}
public class SomeChildClass3
{
public SomeProperty3 SomeProperty3 { get; set; }
public SomePropety4 SomePropety4 { get; set; }
}
bind as below:
var targetobj = new List<BindTarget>();
Configuration.GetSection("TopLevel").Bind(targetobj);
var str = JsonConvert.SerializeObject(targetobj,new JsonSerializerSettings() { NullValueHandling=NullValueHandling.Ignore});
result:
The document related

post array of string from angular js controller to asp controller

I am using visual studio 2017 with asp mvc 5.0 and angularJS v1.6.10. I need to send object from angularJS to asp controller via $http service see the following code
public class Patient
{
public int Age { get; set; }
public byte Gender { get; set; }
public bool IsSmoker { get; set; }
public string[] Symptoms { get; set; }
public bool FractionWithTbPatient { get; set; }
public bool PreviousTbInfection { get; set; }
public bool Inheritedcysricfibrosis { get; set; }
public bool Inheritedasthma { get; set; }
public bool Smokermother { get; set; }
public bool OrganicDust { get; set; }
public bool FractionWithanimals { get; set; }
public bool PreviousSurgery { get; set; }
public bool Longbonebroken { get; set; }
public bool Pregnant { get; set; }
public bool CancerInfection { get; set; }
public bool LongTimeInBed { get; set; }
public bool PreviousInfectionWithPulmonaryEmbolism { get; set; }
}
and the asp controller method is the following
public class ConditionDiagnosisController : Controller{
[HttpPost]
public void GetCaseResult(Patient patient)
{
int i = 0;
i++;
}
}
and the angularJS controller is the follwoing
myApp.controller("mainController",
function ($scope, $http) {
var patient = new Object();
patient.Age = 1;
patient.Gender = 0;
patient.IsSmoker = false;
patient.Inheritedasthma = false;
patient.Symptoms = ['x','y'];
patient.Pregnant = false;
patient.FractionWithTbPatient = false;
patient.PreviousTbInfection = false;
patient.Inheritedcysricfibrosis = false;
patient.Inheritedasthma = false;
patient.Smokermother = false;
patient.OrganicDust = false;
patient.FractionWithanimals = false;
patient.PreviousSurgery = false;
patient.Longbonebroken = false;
patient.Pregnant = false;
patient.CancerInfection = false;
patient.LongTimeInBed = false;
patient.PreviousInfectionWithPulmonaryEmbolism = false;
$scope.go = function () {
$http({
method: "POST",
url: "/ConditionDiagnosis/GetCaseResult",
dataType: 'json',
data: $scope.patient,
headers: { "Content-Type": "application/json" }
});
};
});
when I send it I get in the asp method all values of the object correctly else the Symptoms variable which is a string array, I get it null. Any help?
Try with this data : JSON.stringify($scope.patient)
in the ASP.NET class, you should assign the Array in the constructor.
the issue will be that you can't assign the array so the best way is to use List
change the type of Symptoms to List and then in the constructor write this code:
public Patient(){
Symptoms = new List();
}

A circular reference was detected while serializing an object of type in AngularJs and asp.net mvc

Well I know it is well known error. There are lots of questions asked here. But after going through few questions I am not able to solve my problem I am getting this error my website.
This is my error
A circular reference was detected while serializing an object of type
My Controller Code is
[HttpGet]
public JsonResult Get(int currentPage, int recordsPerPage)
{
var pageNumber = currentPage;
var pageSize = recordsPerPage;
var begin = (pageNumber - 1) * pageSize;
var totalNumberOfRecords = db.Products.Count();
var productlist = db.Products.OrderBy(r => r.ProductID).Skip(begin).Take(pageSize).ToList();
db.Configuration.ProxyCreationEnabled = false;
//var productlist = db.Products.ToList();
var product = new { Product = productlist, TotalRecords = totalNumberOfRecords };
return Json(new { Products = productlist, RecordCount = totalNumberOfRecords }, JsonRequestBehavior.AllowGet);
}
My Angular Controller Code is this
function GetProducts() {
var productResult = productService.getProduct($scope.currentPage, $scope.recordsPerPage);
productResult.then(function (result) {
console.log("d",data);
if (result.data != '' || result.data != null) {
if (result.data != null || result.data != '') {
$scope.Products = result.data;
}
else if (result.data = 0) {
$scope.message = "No Product Found"
}
}
});
};
And Angular Service code is this
this.getProduct = function (currentPage, recordsPerPage) {
return $http.get('/Home/Get?currentPage=' + currentPage + '&recordsPerPage=' + recordsPerPage);
// return $http.get('/Home/Get');
};
I am missing something but I am unable to get that. Any expert please help me in this.. I spend my whole night with this error. I try every solution of stackoverflow which I read but nothing works for me
Here is My Model
namespace StylesStore.Models
{
using System;
using System.Collections.Generic;
public partial class Product
{
public Product()
{
this.Carts = new HashSet<Cart>();
this.OrdersDetails = new HashSet<OrdersDetail>();
}
public int ProductID { get; set; }
public Nullable<int> SKU { get; set; }
public Nullable<int> VendorProductID { get; set; }
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public Nullable<int> SupplierID { get; set; }
public Nullable<int> CategoryID { get; set; }
public Nullable<int> QuantityPerUnit { get; set; }
public decimal UnitPrice { get; set; }
public Nullable<int> MSRP { get; set; }
public Nullable<int> AvailableSize { get; set; }
public string AvailableColor { get; set; }
public Nullable<int> Size { get; set; }
public string Color { get; set; }
public Nullable<int> Discount { get; set; }
public Nullable<int> UnitWeight { get; set; }
public Nullable<int> UnitsInStock { get; set; }
public string UnitsInOrder { get; set; }
public string Picture1 { get; set; }
public string Picture2 { get; set; }
public string Picture3 { get; set; }
public string Picture4 { get; set; }
public Nullable<decimal> ShippingCharges { get; set; }
public string Note { get; set; }
public Nullable<bool> InStock { get; set; }
public Nullable<int> CatID { get; set; }
public Nullable<decimal> wieght { get; set; }
public Nullable<int> totalview { get; set; }
public Nullable<int> Disable { get; set; }
public Nullable<System.DateTime> EntryDate { get; set; }
public virtual ICollection<Cart> Carts { get; set; }
public virtual Category Category { get; set; }
public virtual ICollection<OrdersDetail> OrdersDetails { get; set; }
public virtual Supplier Supplier { get; set; }
}
}
You should not serialize your entity objects. Your entity objects have virtual navigation properties which are detected by JsonSerializer. JsonSerializer thinks they are embedded properties of that object and tries to serialize them too. and this goes on. serializer finds itself trying to serialize all database. this is why your error occurs.
You should either mark fields that need to be serialized or use DTO's to serialize objects.
Note: you can use AutoMapper to map objects between Entity and DTO

How to save FormData into sql

I need to store the path of the file along with its properties into a sql database. Currently all I can do is store the file on the server. I can see the file properties in the controller but I do not know how to access them.
public class File
{
public int FileId { get; set; }
public string FileType { get; set; }
public string FileDate { get; set; }
public string FilePdf { get; set; }
public string FileLocation { get; set; }
public string FilePlant { get; set; }
public string FileTerm { get; set; }
public DateTime? FileUploadDate { get; set; }
public string FileUploadedBy { get; set; }
public string CompanyName { get; set; }
public virtual ApplicationUser User { get; set; }
}
Controller
[HttpPost]
public async Task<HttpResponseMessage> PostFile()
{
if (!Request.Content.IsMimeMultipartContent())
{
this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
var result = await Request.Content.ReadAsMultipartAsync(provider);
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in result.FormData.GetValues("companyname")
.FirstOrDefault())
{
if (key == "companyName")
{
var companyName = val;
var fileDate = val;
var fileLocation = val;
var filePlant = val;
var fileTerm = val;
var fileType = val;
var fileUploadDate = val;
var fileUploadedBy = val;
}
}
}
// On upload, files are given a generic name like "BodyPart_26d6abe1-3ae1-416a-9429-b35f15e6e5d5"
// so this is how you can get the original file name
var originalFileName = GetDeserializedFileName(result.FileData.First());
var uploadedFileInfo = new FileInfo(result.FileData.First().LocalFileName);
string path = result.FileData.First().LocalFileName;
//Do whatever you want to do with your file here
//db.Files.Add();
db.SaveChanges();
return this.Request.CreateResponse(HttpStatusCode.OK, originalFileName);
}
private string GetDeserializedFileName(MultipartFileData fileData)
{
var fileName = GetFileName(fileData);
return JsonConvert.DeserializeObject(fileName).ToString();
}
public string GetFileName(MultipartFileData fileData)
{
return fileData.Headers.ContentDisposition.FileName;
}
Try using a function like this. You can replace with
private object GetFormData<T>(MultipartFormDataStreamProvider result)
{
if (result.FormData.HasKeys())
{
var unescapedFormData = Uri.UnescapeDataString(result.FormData
.GetValues(0).FirstOrDefault() ?? String.Empty);
if (!String.IsNullOrEmpty(unescapedFormData))
return JsonConvert.DeserializeObject<T>(unescapedFormData);
}
return null;
}
Use it like this
File file = GetFormData(result);
The main line of code you want is:
JsonConvert.DeserializeObject<File>(result.FormData.GetValues(0).FirstOrDefault());

Sending object to sql server in ASP.NET MVC4 Architecture

I am getting an exception on db.CrimeReports.Add(i);
"An exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll but was not handled in user code "
[HttpPost]
public void Test(HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
using (UsersContext db = new UsersContext())
{
//db.LoginData.Add(new LoginData { UserId = 4, Username = "maria", Password ="rahat"});
byte[] image = new byte[file.ContentLength];
file.InputStream.Read(image, 0, image.Length);
var i = new CrimeReport { ImageName = "murder", ImageContent = image, Active =false};
db.CrimeReports.Add(i);
db.SaveChanges();
}
}
else
{
ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
}
}
Here is my CrimeReport class
[Table("CrimeReport")]
public class CrimeReport
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int ImageId { get; set; }
public string ImageName { get; set; }
public byte[] ImageContent { get; set; }
public string Createdby { get; set; }
public System.DateTime CreatedDt { get; set; }
string Updatedby { get; set; }
public Nullable<System.DateTime> UpdatedDt { get; set; }
public bool Active { get; set; }
public virtual ReportDescription ReportDescription { get; set; }
}

Resources