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

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.

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

How to pass an array in formData

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:

How can I fill array with model properties in controller action and pass to view?

I have a model with a table namely Resource that consist of multiple properties. I want define an array and fill that with Id,Latitude and Longitude properties in action namely DistanceMCalculate() in controller and pass this array to javascript in view in my MVC project.
This is my model in edmx:
public partial class Resource
{
public int Id { get; set; }
public int Code { get; set; }
public string Name { get; set; }
public Nullable<System.DateTime> StartHour { get; set; }
public string Address { get; set; }
public Nullable<System.DateTime> Arrivetime { get; set; }
public Nullable<int> ArriveTimeDuration { get; set; }
public Nullable<int> ProgressPercent { get; set; }
public Nullable<int> ResourceTypeId { get; set; }
public Nullable<decimal> Latitude { get; set; }
public Nullable<decimal> Longitude { get; set; }
public virtual ResourceType ResourceType { get; set; }
}
}
And this is my action and I want add Id,Latitude and Longitude properties of model to an array(arraylist) and pass to view in javascript. I need just array in view.how can I do it?
public ActionResult DistanceMCalculate()
{
var model= db.Resource.Where(p => p.ResourceTypeId == 1 && p.Latitude != null).ToList();
return Json();
}
Thanks a lot
Try this:
public decimal?[][] DistanceMCalculate()
{
var result= db.Resource
.Where(p => p.ResourceTypeId == 1 && p.Latitude != null)
.Select(x => new decimal?[] { x.Id, x.Latitude, x.Longitude })
.ToArray();
return result;
}

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()));

Unable to deserialize a JSON string generated by a JQuery plugin

I using a JQuery plugin that enable my users to design forms. The design is saved in form of a JSON string in database. This JSON string is in following format:
{
"fields": [{
"label": "Untitled",
"field_type": "text",
"required": true,
"field_options": {
"save_to": "",
"size": "small",
"description": ""
},
"cid": "c5"
}]
}
Following is C# class structure and code that is used to deserialize this JSON string:
public class Options {
public string label {
get;
set;
}
public bool Checked {
get;
set;
}
}
public class FieldOption {
public string save_to {
get;
set;
}
public string description {
get;
set;
}
public object options {
get;
set;
}
public bool include_other_option {
get;
set;
}
public string size {
get;
set;
}
}
public class DesignField {
public string label {
get;
set;
}
public string field_type {
get;
set;
}
public bool required {
get;
set;
}
public string cid {
get;
set;
}
public List < FieldOption > field_options {
get;
set;
}
}
public class Design {
public List < DesignField > fields {
get;
set;
}
}
public partial class FormDesign: System.Web.UI.UserControl {
List < DesignField > FormFields;
public string FormDesignData {
get;
set;
}
protected void Page_Load(object sender, EventArgs e) {
Design res = JsonHelper.JsonDeserialize < Design > (FormDesignData);
}
}
JSON Helper class is given here: http://www.codeproject.com/Articles/272335/JSON-Serialization-and-Deserialization-in-ASP-NET
The problem is that it is deserializing when inner JSON objects are enclosed with [] for example:
"field_options":[{
"save_to": "",
"size": "small",
"description": ""
}]
But the plugin is not exporting the JSON in that format but in the format I mentioned before.
Please tell me how can I convert it to a valid deserializable format?
The model according to your json should be:
public class FieldOptions
{
public string save_to { get; set; }
public string size { get; set; }
public string description { get; set; }
}
public class Field
{
public string label { get; set; }
public string field_type { get; set; }
public bool required { get; set; }
public FieldOptions field_options { get; set; }
public string cid { get; set; }
}
public class RootObject
{
public List<Field> fields { get; set; }
}
I used this online tool http://json2csharp.com/ to generate it.
RootObject is the type you will use to deserialize
Using, for ex, Json.Net, your code would be
var myobj = JsonConvert.DeserializeObject<RootObject>(json);

Categories