Telerik Kendo DropDown sends the previous value to the Controller - javascript

I have been working in ASP MVC (C#) razor Entity Framework project, Visual Studio 2012, that uses Telerik Kendo DropDown:
#(Html.Kendo().DropDownListFor(run => run.Repair)
.Name("Repair")
.OptionLabel(RunStrings.Select)
.DataTextField("Text")
.DataValueField("Value")
.DataSource(dataSource => dataSource
.Read(read => read.Action("GetRepairCodes", "Run")
)
)
.Value(myModel.Repair.ToString())
.HtmlAttributes(new { style = "width:50% !important;" })
.Events( e => e.Change("RepairDropDown_OnChange")))
The DropDown sends its value to the Controller, in the object outcomeModel. The code of the Controller is:
public ActionResult OutcomeEdit(OutcomeModel outcomeModel, string previous, string next, string finish)
{
Run run = Session["Run"] as Run;
if (run == null) return RedirectToAction("Index", "Home", new { area = "" });
if (ModelState.IsValid)
{
outcomeModel.CopyToRun(run);
Repository myRepo = new Repository();
myRepo.UpdateOutcome(run);
// now update the Organ failure column
string organFailureString = string.Empty;
if (run.Discontinuation == Discontinuation.DiedOrganFailure && ModelState["OrganFailureType"] != null)
{
organFailureString = outcomeModel.DecodeOrganFailureFromString(ModelState["OrganFailureType"].Value.AttemptedValue).ToString();
myRepo.UpdateOrganFailureValue(run.RunId, organFailureString);
}
else
{
run.OrganFailure = null;
myRepo.UpdateOutcome(run);
}
/***
* This will redirect user to a selected tab
*/
string jumptToTab = Request.Form["JumpToTab"];
if (jumptToTab != "-1")
{
TabIndex gotoindex = (TabIndex)Convert.ToInt32(jumptToTab);
TempData["TabIndex"] = (int)gotoindex;
return RedirectToAction(GiveLinkToPage(gotoindex));
}
// continue normally
// Find which command was selected (non-null parameter)
var selection = (new[] { previous, next, finish })
.Select((item, index) => new { ItemName = item, Position = index })
.First(x => x.ItemName != null);
TabIndex currentTab = TabIndex.SeverityScores;
LinkDirection command = LinkDirection.Finish;
if (selection.Position == 0) { command = LinkDirection.Previous; }
if (selection.Position == 1) { command = LinkDirection.Next; }
if (selection.Position == 2) { command = LinkDirection.Finish; }
TempData.Keep("TabIndex");
TempData["TabIndex"] = this.GiveFutureTabIndex(command, currentTab);
string link = this.GiveFutureLink(command, currentTab);
return RedirectToAction(link);
}
return View(outcomeModel);
}
But, in outcomeModel, in Repair property, in debugger I always see the previous value of the DropDown, not that value which is chosen. I cannot find the reason why. So, I decided to set the value of the DropDown by force of in the JavaScript OnChange event of the DropDown:
<script>
function RepairDropDown_OnChange(e) {
console.log('RepairDropDown_OnChange');
console.log('Model ' + e.model);
console.log('Container ' + e.container.find('#Repair').length);
e.model.set("Repair", e.container.find('#Repair').val());
}
</script>
But, in Console of the Browser I see that e.model is undefined. How can I solve the bug? Thank you in advance for any help.
UPDATE
OutcomeModel is :
public class OutcomeModel : RunModelBase
{
#region Construction
public OutcomeModel() { }
public OutcomeModel(Run run)
{
if (Mapper.FindTypeMapFor<DateTimeOffset, DateTime>() == null)
{
Mapper.CreateMap<DateTimeOffset, DateTime>().ConvertUsing<DateTimeOffsetConverter>();
}
if (Mapper.FindTypeMapFor<Run, OutcomeModel>() == null)
{
Mapper.CreateMap<Run, OutcomeModel>()
.ForMember(dest => dest.UniqueId, opt => opt.MapFrom(src => src.Patient.UniqueId))
.ForMember(dest => dest.Birthdate, opt => opt.MapFrom(src => src.Patient.Birthdate))
.ForMember(dest => dest.Sex, opt => opt.MapFrom(src => src.Patient.Sex))
.ForMember(dest => dest.Race, opt => opt.MapFrom(src => src.Patient.Race))
.IgnoreAllNonExisting();
Mapper.AssertConfigurationIsValid();
}
Mapper.Map(run, this);
}
#endregion Construction
#region Properties
public string OrganFailureType { get; set; }
[Display(Name = "Discontinuation", Description = "DiscontinuationDescription", ResourceType = typeof(RunStrings))]
[UIHint("Enum")]
public Discontinuation? Discontinuation { get; set; }
[Display(Name = "OrganFailure", Description = "OrganFailureDescription", ResourceType = typeof(RunStrings))]
public OrganFailure OrganFailure { get; set; }
[Display(Name = "DischargedAlive", Description = "DischargedAliveDescription", ResourceType = typeof(RunStrings))]
public bool? DischargedAlive { get; set; }
[Display(Name = "DischargeLocation", Description = "DischargeLocationDescription", ResourceType = typeof(RunStrings))]
[UIHint("Enum")]
public DischargeLocation? DischargeLocation { get; set; }
[Display(Name = "ExtubationDate", Description = "ExtubationDateDescription", ResourceType = typeof(RunStrings))]
[DisplayFormat(DataFormatString = "{0:f}")]
[CompareValues("IntubationDate", CompareValues.GreaterThanOrEqualTo, ErrorMessageResourceName = "ExtubationDateError", ErrorMessageResourceType = typeof(RunStrings))]
[CompareValues("AdmitDate", CompareValues.GreaterThanOrEqualTo, ErrorMessageResourceName = "ExtubationDateError", ErrorMessageResourceType = typeof(RunStrings))]
public DateTime? ExtubationDate { get; set; }
[Display(Name = "DischargeDate", Description = "DischargeDateDescription", ResourceType = typeof(RunStrings))]
[DisplayFormat(DataFormatString = "{0:f}")]
[CompareValues("IntubationDate", CompareValues.GreaterThanOrEqualTo, ErrorMessageResourceName = "DischargeDateError", ErrorMessageResourceType = typeof(RunStrings))]
[CompareValues("AdmitDate", CompareValues.GreaterThanOrEqualTo, ErrorMessageResourceName = "DischargeDateError", ErrorMessageResourceType = typeof(RunStrings))]
public DateTime? DischargeDate { get; set; }
[Display(Name = "DeathDate", Description = "DeathDateDescription", ResourceType = typeof(RunStrings))]
[DisplayFormat(DataFormatString = "{0:f}")]
[CompareValues("IntubationDate", CompareValues.GreaterThanOrEqualTo, ErrorMessageResourceName = "DeathDateError", ErrorMessageResourceType = typeof(RunStrings))]
[CompareValues("AdmitDate", CompareValues.GreaterThanOrEqualTo, ErrorMessageResourceName = "DeathDateError", ErrorMessageResourceType = typeof(RunStrings))]
public DateTime? DeathDate { get; set; }
[Display(Name = "Repair", Description = "RepairDescription", ResourceType = typeof(RunStrings))]
public short? Repair { get; set; }
// Following properties are in model for validation, but are not copied/persisted
public DateTime? AdmitDate { get; set; }
public DateTime? IntubationDate { get; set; }
#endregion Properties
UPDATE2
myModel is:
ELSORegistry.DataAccess.Run myModel = Session["run"] as ELSORegistry.DataAccess.Run;

Related

How to get value from a dropdownlist selection listed by another dropdownlist

I have a dropdown list using another dropdown list. The issue i am facing is that I am able to retrieve the choice of the first dropdown list but not the second one.
Here is my script under view
$(function() {
$("#Off").change(function() {
$.get("/Reference/GetSubjectById", {
id: $("#Off").val()
}, function(data) {
$("#Su").empty() $.each(data, function(mail, row) {
$("#Su").append(" <option value='" + row.Id_Subject + "'>" + row.Subject_Matter + "</option>")
});
})
});
});
Here my controller
public ActionResult Mail()
{
fillingEntities db = new fillingEntities();
ViewBag.OfficeName = new SelectList(db.offices, "Office_Id", "Office_Name");
//ViewBag.SubjectName = new SelectList(db.subjects, "Subject_Id", "Subject_Matter");
MailViewModel mailView = new MailViewModel();
mailView.date = DateTime.Now;
return View(mailView);
}
public JsonResult GetSubjectById(int id)
{
fillingEntities db = new fillingEntities();
db.Configuration.ProxyCreationEnabled = false;
return Json(db.subjects.Where(m => m.Office_Id == id), JsonRequestBehavior.AllowGet);
}
public ActionResult New(int newref)
{
return View();
}
public ActionResult Save(MailViewModel mail)
{
fillingEntities db = new fillingEntities();
//subject mySubject = db.subjects.Where(m => m.Subject_Id == mail.id_subject).FirstOrDefault();
string subValue = Request.Form["Su"].ToString();
reference lastRef = db.references.ToList().LastOrDefault();
int numeroRef = (lastRef.Opening_Ref+1);
//string referenceNumber = mySubject.Subject_Code + "/" + numeroRef + "/" + "2020";
string referenceNumber = subValue + "/" + numeroRef + "/" + "2020";
mail.NewReference = referenceNumber;
reference newRef = new reference();
newRef.Opening_Ref = numeroRef;
db.references.Add(newRef);
db.SaveChanges();
mail newMail = new mail();
newMail.Location = mail.location;
newMail.Mail_Year = (short) DateTime.Now.Year;
newMail.Mail_Date = DateTime.Now.Date;
newMail.Addressed_Name = mail.addTo;
newMail.Addressed_Department = mail.addDep;
newMail.Addressed_Organisation = mail.addOrg;
newMail.Mail_Subject = mail.subject;
newMail.Reference_Id = newRef.Reference_Id;
newMail.Office_Id = mail.id_office;
db.mails.Add(newMail);
db.SaveChanges();
return View("Save", mail);
}
And finaly my viewmodel
namespace FillingSystem.ViewModel
{
public class MailViewModel
{
public string addTo { get; set; }
public string addOrg { get; set; }
public string addDep { get; set; }
public string subject { get; set; }
public string location { get; set; }
public DateTime year { get; set; }
public DateTime date { get; set; }
public IEnumerable<office> offices { get; set; }
public int id_office { get; set; }
public int id_subject { get; set; }
public IEnumerable<subject> subjects { get; set; }
public int Opening_Ref { get; set; }
public string NewReference { get; set; }
}
}

JavaScript - Put arrays into view model then return model via AJAX

I have arrays that are created in my javascript, for example here is how one array is created
$("button").click(function () {
//var token = $("input[name='__RequestVerificationToken']", "#__AjaxAntiForgeryForm").val();
var partArray = []; //for creating json array
//looping through trs with class tr_clonePart
$(".tr_clonePart").each(function () {
//for storing qtys and radios of cloned and original
var qty_actiontype_cloned = []
var datas_cloned = {};
var data_original = {}//fro original
var qty_actiontype_original = [];
//get infos for various fields
var p_id = $(this).find("td > a").attr('p-id');
var mfg = $(this).find("input.part_mfg").val();
var part_name = $(this).find("input.part_name").val();
var qty_in_item = $(this).find("input.qty_in_item").val();
var item = {};
//add values in json objects
item["PartID"] = p_id
item["MFGNumber"] = mfg
item["PartName"] = part_name
item["QtyInItem"] = qty_in_item
//chcking if part-class is checked or not
if ($(this).find("input[type='checkbox'].part-class").is(':checked')) {
var move_all = $(this).find("input[type='checkbox'].part-class").val();
//item["MoveAll"] = move_all
item["MoveAll"] = (move_all == "true");
var radios = $(this).find("input[type='radio'].radios:checked").val();
data_original["action_type"] = radios //adding value of radios in array
//item['radios_c'] = radios_c
var qty = $(this).find("input.qty").val();
data_original["qty"] = qty //adding value of qty in array
qty_actiontype_original.push(data_original)
item["QtyActionTypeOriginal"] = qty_actiontype_original
//item["qty"] = qtys
} else {
var qty = $(this).find("input.qty").val();
//for original data
data_original["qty"] = qty
var radios = $(this).find("input[type='radio'].radios:checked").val();
//for original data
data_original["action_type"] = radios
qty_actiontype_original.push(data_original)
item["QtyActionTypeOriginal"] = qty_actiontype_original
//item["MoveAll"] = "false"
item["MoveAll"] = (move_all == "false");
//looping through cloned trs
$(".tr_clonePart_" + p_id).each(function () {
var radios_clones = $(this).find("input[type='radio'].radios:checked").val();
//puuting value in cloned array
datas_cloned["action_type"] = radios_clones
console.log(radios_clones)
var qty_clones = $(this).find("input.qty").val();
datas_cloned["qty"] = qty_clones
//push data in cloned array
qty_actiontype_cloned.push(datas_cloned)
});
//push array in cloned json object
item["QtyActionTypeCloned"] = qty_actiontype_cloned
}
//getting other values
var onHand = $(this).find("input.OnHand").val();
var onWorkOrder = $(this).find("input.onWorkOrder").val();
var committed = $(this).find("input.committed").val();
var fstk = $(this).find("input.fstk").val();
item["OnHand"] = onHand
item["OnWorkOrder"] = onWorkOrder
item["Committed"] = committed
item["FSTK"] = fstk
//push json object in array
partArray.push(item)
})
But i want to be able to put the 'partArray' into my itemViewModel that looks like this
public class ItemViewModel
{
[Required]
public int Id { get; set; }
[Required]
public int JobId { get; set; }
public string ItemId { get; set; }
public string ItemName { get; set; }
public string MFGNumber { get; set; }
public IList<ItemPartViewModel> Parts { get; set; }
public IList<ItemComponentViewModel> Components{ get; set; }
public IList<ComponentPartViewModel> ComponentParts { get; set; }
public IList<ComponentSubCompViewModel> ComponentSubComps { get; set; }
public IList<SubCompPartViewModel> SubCompParts { get; set; }
public IList<SubCompSubCompViewModel> SubCompSubComps { get; set; }
public IList<SubCompSubCompPartViewModel> SubCompSubCompParts { get; set; }
}
if it helps here is my itemPartViewModel layout, (all the other ILists have the same layout)
public class ItemPartViewModel
{
[Required]
public int ID { get; set; }
public int ItemID { get; set; }
public string PartID { get; set; }
public string MFGNumber { get; set; }
public string PartName { get; set; }
public float QtyInItem { get; set; }
public float Qty { get; set; }
public bool MoveAll { get; set; }
public float OnHand { get; set; }
public float OnWorkOrder { get; set; }
public float Committed { get; set; }
public float FSTK { get; set; }
public QtyActionTypeCloned[] qty_actiontype_cloned { get; set; }
public QtyActionTypeOriginal[] qty_actiontype_original { get; set; }
// This is the additional property to contain what user picks
public PartActionType SelectedActionType { get; set; }
}
So I am wondering how I can put every array that is created, into my itemViewModel and then pass the entire ViewModel into the controller method?
Here is my AJAX
$.ajax({
type: "POST",
url: "#IGT.baseUrl/JODetails/SpecialOrderSelection",
contentType: "application/json; charset=utf-8",
data:
JSON.stringify({ itemViewModel: myData }),
dataType: "json",
traditional: true,
success: function () {
alert('Success!');
},
error: function () {
alert('Error! ');
}
});
Is this possible and how can it be done?
This is a guess but would it not be
var myData = {
Id: idValue,
JobId: jobIdValue,
ItemId: itemIdValue,
ItemName: itemNameValue,
MFGNumber: mfgNumberValue,
Parts: partArray,
Components: componentArray,
ComponentParts: componentPartArray,
ComponentSubComps: componentSubCompsArray,
SubCompParts: subCompPartsArray,
SubCompSubComps: subCompSubCompsArray,
SubCompSubCompParts:subCompSubCompPartsArray
}
var ajaxData = JSON.stringify({myViewModel: myData});
Then the post method in the controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SpecialOrderSelection(ItemViewModel myViewModel)
{
//rest of post method
}
Also on the client qty_actiontype_cloned and qty_actiontype_original are arrays. So I suggest that in your ItemPartViewModel you change
public QtyActionTypeCloned qty_actiontype_cloned { get; set; }
public QtyActionTypeOriginal qty_actiontype_original { get; set; }
to
public QtyActionTypeCloned[] qty_actiontype_cloned { get; set; }
public QtyActionTypeOriginal[] qty_actiontype_original { get; set; }
Also looks like your client names are not matching the server names. To fix you either need to change on the client i.e.
item["QtyActionTypeOriginal"] = qty_actiontype_original
needs to become
item["qty_actiontype_original"] = qty_actiontype_original
or on the server i.e.
public QtyActionTypeOriginal[] qty_actiontype_original { get; set; }
needs to become
public QtyActionTypeOriginal[] QtyActionTypeOriginal{ get; set; }

A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule' MVC JSON

I need to display a table with the help of Json but i am getting error.
A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'
Index.cshtml
var table = $('#maintable').DataTable({
"ajax": {
"type": "POST",
"url": '#Url.Action("BindDatatable", "Sales")',
"data": { itemtyyID: $("#ddl_item").val(), itloccid: $("#getlocation").val() },
//"contentType": application/json,
"traditional": true,
"datatype": "json",
"dataSrc": function (json) {
//Make your callback here.
alert("Done!");
// var x = JSON.parse(json);
// return x;
return json.data;
}
},
"columns": [
{ "data": "Item", "autowidth": true },
{ "data": "qty", "autowidth": true },
{ "data": "rate", "autowidth": true },
{ "data": "ppb", "autowidth": true, "visible": false }
],
select: true
});
SalesController.cs
[HttpPost]
public JsonResult BindDatatable(string itemtyyID, string itloccid)
{
Int32 itemtyyIDD, itloccIDD;
DataSet ds = new DataSet();
if (!string.IsNullOrEmpty(itemtyyID) && !string.IsNullOrEmpty(itloccid))
{
itemtyyIDD = Convert.ToInt32(itemtyyID);
itloccIDD = Convert.ToInt32(itloccid);
}
else
{
itemtyyIDD = 0;
itloccIDD = 0;
}
DataTable dt = new DataTable();
OracleCommand cmdsp = new OracleCommand();
cmdsp.CommandType = System.Data.CommandType.StoredProcedure;
cmdsp.CommandText = "Pkg_Inventory.Prc_sale_stock";
cmdsp.Parameters.Add("ITEMYYID", OracleType.Int32, 25).Value = itemtyyIDD;
cmdsp.Parameters.Add("ITLOCID", OracleType.Int32, 25).Value = itloccIDD;
cmdsp.Parameters.Add("SALESTOCK", OracleType.Cursor).Direction = ParameterDirection.Output;
cmdsp.Parameters.Add("Pmsg", OracleType.VarChar, 10).Direction = ParameterDirection.Output;
dt = MyContext.FillDataTable(cmdsp);
List<justatest.Models.SalesModel.Sales> details = new List<justatest.Models.SalesModel.Sales>();
if (cmdsp.Parameters["Pmsg"].Value.ToString() == "T")
{
foreach (DataRow dtrow in dt.Rows)
{
justatest.Models.SalesModel.Sales user = new justatest.Models.SalesModel.Sales();
user.Item = dtrow["item"].ToString();
user.qty = dtrow["quan"].ToString();
user.rate = dtrow["rate"].ToString();
user.ppb = dtrow["price_bag"].ToString();
details.Add(user);
}
}
var data = details.ToArray();
return Json(new { data = data}, JsonRequestBehavior.AllowGet);
}
Model(Sales.cs)
public class Sales
{
public Sales() { }
public string Item { get; set; }
public string Loc { get; set; }
public Int64 ID { get; set; }
public Int64 SALES_R_ID { get; set; }
public Int64 car_IDD { get; set; }
public Int64 driver_IDD { get; set; }
public Int64 labor_IDD { get; set; }
public string qty { get; set; }
public Int64 t_qty { get; set; }
public Int64 ship_qty { get; set; }
public string rate { get; set; }
public string ppb { get; set; }
public string inv_lock_id { get; set; }
public string Nameofcustomer { get; set; }
public string Descrip { get; set; }
public DateTime Date { get; set; }
public Int32 InvoiceID { get; set; }
public Int32 TotAmount { get; set; }
public Int32 Disc { get; set; }
public Int32 GTotal { get; set; }
public Int32 Customer_Presence { get; set; }
public Int32 paid { get; set; }
public Int32 pay_amt { get; set; }
public Int32 ship { get; set; }
public Int32 shipamt { get; set; }
public Int32 trips_no { get; set; }
public Int32 bags_no { get; set; }
[Required(ErrorMessage = "Customer Name is Required")]
public string Customer_Name { get; set; }
[MaxLength(7)]
[MinLength(1)]
[RegularExpression("^[0-9]*$", ErrorMessage = "Loan must be numeric")]
public string LoanAmount { get; set; }
[MaxLength(7)]
[MinLength(1)]
[RegularExpression("^[0-9]*$", ErrorMessage = "Loan must be numeric")]
public string ReceivedLoan { get; set; }
public DataTable GetItems()
{
//this.Address = "N/A";
DataTable dt = new DataTable();
OracleCommand CmdCommand = new OracleCommand();
CmdCommand.CommandType = System.Data.CommandType.StoredProcedure;
CmdCommand.CommandText = "Pkg_Inventory.PRC_Shop_Sale_Stock";
CmdCommand.Parameters.Add("SHOPSALE", OracleType.Cursor).Direction = ParameterDirection.Output;
CmdCommand.Parameters.Add("PMSG", OracleType.VarChar, 10).Direction = ParameterDirection.Output;
dt = MyContext.FillDataTable(CmdCommand);
return dt;
}
//For Item List
public System.Web.Mvc.SelectList DT1SelectList(DataTable de, string valueField, string textField, object selectedvalue)
{
if (de == null || valueField == null || valueField.Trim().Length == 0
|| textField == null || textField.Trim().Length == 0)
return null;
var list = new List<Object>();
for (int i = 0; i < de.Rows.Count; i++)
{
list.Add(new
{
value = de.Rows[i][valueField].ToString(),
text = de.Rows[i][textField].ToString()
});
}
return new System.Web.Mvc.SelectList(list.AsEnumerable(), "value", "text", selectedvalue);
}
//For Car
public System.Web.Mvc.SelectList DT2SelectList(DataTable de, string valueField, string textField, object selectedvalue)
{
if (de == null || valueField == null || valueField.Trim().Length == 0
|| textField == null || textField.Trim().Length == 0)
return null;
var list = new List<Object>();
for (int i = 0; i < de.Rows.Count; i++)
{
list.Add(new
{
value = de.Rows[i][valueField].ToString(),
text = de.Rows[i][textField].ToString()
});
}
return new System.Web.Mvc.SelectList(list.AsEnumerable(), "value", "text", selectedvalue);
}
//For Driver
public System.Web.Mvc.SelectList DT3SelectList(DataTable de, string valueField, string textField, object selectedvalue)
{
if (de == null || valueField == null || valueField.Trim().Length == 0
|| textField == null || textField.Trim().Length == 0)
return null;
var list = new List<Object>();
for (int i = 0; i < de.Rows.Count; i++)
{
list.Add(new
{
value = de.Rows[i][valueField].ToString(),
text = de.Rows[i][textField].ToString()
});
}
return new System.Web.Mvc.SelectList(list.AsEnumerable(), "value", "text", selectedvalue);
}
//For Labor
public System.Web.Mvc.SelectList DT4SelectList(DataTable de, string valueField, string textField, object selectedvalue)
{
if (de == null || valueField == null || valueField.Trim().Length == 0
|| textField == null || textField.Trim().Length == 0)
return null;
var list = new List<Object>();
for (int i = 0; i < de.Rows.Count; i++)
{
list.Add(new
{
value = de.Rows[i][valueField].ToString(),
text = de.Rows[i][textField].ToString()
});
}
return new System.Web.Mvc.SelectList(list.AsEnumerable(), "value", "text", selectedvalue);
}
//For sales Invoice
public DataTable GetInvoice()
{
DataTable dt = new DataTable();
OracleCommand CmdCommand = new OracleCommand();
CmdCommand.CommandType = System.Data.CommandType.StoredProcedure;
CmdCommand.CommandText = "Pkg_Sales.Prc_Show_Invoice";
CmdCommand.Parameters.Add("SALES_REF_ID", OracleType.Int32, 25).Value = InvoiceID;
CmdCommand.Parameters.Add("SALECUR", OracleType.Cursor).Direction = ParameterDirection.Output;
CmdCommand.Parameters.Add("PMSG", OracleType.VarChar, 10).Direction = ParameterDirection.Output;
dt = MyContext.FillDataTable(CmdCommand);
return dt;
}
//For sales Details
public DataTable GetSaleDetails()
{
DataTable dt = new DataTable();
OracleCommand CmdCommand = new OracleCommand();
CmdCommand.CommandType = System.Data.CommandType.StoredProcedure;
CmdCommand.CommandText = "Pkg_Sales.Prc_Show_Sale_Details";
CmdCommand.Parameters.Add("SALES_REF_ID", OracleType.Int32, 25).Value = InvoiceID;
CmdCommand.Parameters.Add("SALECUR", OracleType.Cursor).Direction = ParameterDirection.Output;
CmdCommand.Parameters.Add("PMSG", OracleType.VarChar, 10).Direction = ParameterDirection.Output;
dt = MyContext.FillDataTable(CmdCommand);
return dt;
}
//For Item Details
public DataTable GetItemDetails()
{
DataTable dt = new DataTable();
OracleCommand CmdCommand = new OracleCommand();
CmdCommand.CommandType = System.Data.CommandType.StoredProcedure;
CmdCommand.CommandText = "Pkg_Sales.Prc_Show_Item_Details";
CmdCommand.Parameters.Add("SALES_REF_ID", OracleType.Int32, 25).Value = InvoiceID;
CmdCommand.Parameters.Add("SALECUR", OracleType.Cursor).Direction = ParameterDirection.Output;
CmdCommand.Parameters.Add("PMSG", OracleType.VarChar, 10).Direction = ParameterDirection.Output;
dt = MyContext.FillDataTable(CmdCommand);
return dt;
}
//For Item Shipment
public DataTable GetItemShipment()
{
DataTable dt = new DataTable();
OracleCommand CmdCommand = new OracleCommand();
CmdCommand.CommandType = System.Data.CommandType.StoredProcedure;
CmdCommand.CommandText = "Pkg_Sales.PRC_Ship_Details";
CmdCommand.Parameters.Add("SALE_R_ID", OracleType.Int32, 25).Value = InvoiceID;
CmdCommand.Parameters.Add("SHIPCURSOR", OracleType.Cursor).Direction = ParameterDirection.Output;
CmdCommand.Parameters.Add("PMSG", OracleType.VarChar, 10).Direction = ParameterDirection.Output;
dt = MyContext.FillDataTable(CmdCommand);
return dt;
}
public DataTable SaleDetails
{
get { return GetSaleDetails(); }
}
public DataTable ItemDetails
{
get { return GetItemDetails(); }
}
public DataTable ItemShipment
{
get { return GetItemShipment(); }
}
public string JavascriptToRun { get; set; }
}
StackTrace
<!DOCTYPE html>
<html>
<head>
<title>A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'.</title>
<meta name="viewport" content="width=device-width" />
<style>
body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
.marker {font-weight: bold; color: black;text-decoration: none;}
.version {color: gray;}
.error {margin-bottom: 10px;}
.expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
#media screen and (max-width: 639px) {
pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
}
#media screen and (max-width: 479px) {
pre { width: 280px; }
}
</style>
</head>
<body bgcolor="white">
<span><H1>Server Error in '/justatest' Application.<hr width=100% size=1 color=silver></H1>
<h2> <i>A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'.</i> </h2></span>
<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
<b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
<br><br>
<b> Exception Details: </b>System.InvalidOperationException: A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'.<br><br>
<b>Source Error:</b> <br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code>
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code>
</td>
</tr>
</table>
<br>
<b>Stack Trace:</b> <br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
[InvalidOperationException: A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'.]
System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +1767
System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +166
System.Web.Script.Serialization.JavaScriptSerializer.SerializeCustomObject(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +793
Circular references in your object hierarchy which is not supported by the JSON serializer.
You need to have something like:
return Json(new {
PropertyA = data.PropertyA,
PropertyB = data.PropertyB,
PropertyC = data.PropertyC,
}, JsonRequestBehavior.AllowGet);
I solve this question with code below
public async Task<JsonResult> GetAll(int id)
{
using (Context context = new Context())
{
var menus = context.GetAll(id);
List<MenuView> menusView = Mapper.Map<List<Menu>, List<MenuView>>(menus);
//Solve circular reference on JSONResult
var result = JsonConvert.SerializeObject(menusView, Formatting.Indented,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
return Json(result, JsonRequestBehavior.AllowGet);
}
}
I Added this code in my Control, in the Client Side i used JSON.parse() for make object.

JSON.stringify child array is empty on Controller

There are a lot of these types of questions, and looking at all of them, I'm not particularly sure what the difference is with my setup.
I've tried a few different variations of the ajax data and how to format the JSON, but this seems to get me the closest. I've done this quite a few times before, and I never ran into this issue.
When I hit the controller, modelDetails is a full object, and ScopeRecord is populated with data. However, each child array is empty -- including ProcedureFields, which isn't making sense. It's not null, but the count is 0.
Simplified js:
$("#submitButton")
.click(function() {
var result = {};
result.ScopeRecord = {};
result.ScopeRecord.ReferenceNumber = "testing123";
result.RoomFields = [];
result.BioFields = [];
result.ReprocessingFields = [];
result.CultureFields = [];
result.ProcedureFields = [];
var fieldInfo = {};
//examDate
fieldInfo.FieldID = 1;
fieldInfo.FieldValue = "test me";
fieldInfo.ItemHistoryID = 3;
fieldInfo.AssociationID = 2;
fieldInfo.IsModified = 1;
result.ProcedureFields.push(fieldInfo);
result.ProcedureFields.push(fieldInfo);
result.ProcedureFields.push(fieldInfo);
var options = {};
options.url = "/MyController/SaveDetails";
options.type = "POST";
options.traditional = true;
var test = JSON.stringify(result);
options.data = test;
options.contentType = "application/json; charset=UTF-8";
options.dataType = "json";
$.ajax(options);
});
My data on the request:
"{
"ScopeRecord":
{
"ReferenceNumber":"testing123"
},
"RoomFields":[],
"BioFields":[],
"ReprocessingFields":[],
"CultureFields":[],
"ProcedureFields":
[{
"FieldID":1,
"FieldValue":"test me",
"ItemHistoryID":3,
"AssociationID":2,
"IsModified":1
},
{
"FieldID":1,
"FieldValue":"test me",
"ItemHistoryID":3,
"AssociationID":2,
"IsModified":1
},
{
"FieldID":1,
"FieldValue":"test me",
"ItemHistoryID":3,
"AssociationID":2,
"IsModified":1
}]
}"
Controller:
[HttpPost]
public ActionResult SaveDetails(RecordDetails modelDetails)
{
....
}
Model:
public class RecordDetails
{
public ScopeRecord ScopeRecord { get; set; }
public List<FieldInfo> ProcedureFields = new List<FieldInfo>();
public List<FieldInfo> RoomFields = new List<FieldInfo>();
public List<FieldInfo> BioFields = new List<FieldInfo>();
public List<FieldInfo> ReprocessingFields = new List<FieldInfo>();
public List<FieldInfo> CultureFields = new List<FieldInfo>();
}
public class FieldInfo
{
public int ItemHistoryID { get; set; }
public int FieldID { get; set; }
public string FieldValue { get; set; }
public bool IsModified { get; set; }
public int? AssociationID { get; set; }
}
I've tried options.data = { modelDetails : JSON.stringify(result) }; but that gives me a 500 error.
What part am I missing?
The DefaultModelBinder cannot set the value of fields. You need to make your collections properties by adding a getter/setter
public class RecordDetails
{
public ScopeRecord ScopeRecord { get; set; }
public List<FieldInfo> ProcedureFields { get; set; }
public List<FieldInfo> RoomFields = { get; set; }
....

Ajax call ASP.NET MVC + Jquery return "Cannot read property 'Description' of undefined"

I´m trying to get data using Ajax, the Ajax call is working fine the problem is that it´s retuning "Cannot read property 'Description' of undefined". Here is the code:
Quarters Model
public class Quarters
{
[Key]
[Display(Name="Code")]
public Int32 QuarterId { get; set; }
[Display(Name = "Description")]
public String Description { get; set; }
}
Months Model
public class Months
{
[Key]
[Display(Name = "Code")]
public Int32 MonthId { get; set; }
[Display(Name = "Description")]
public String Description { get; set; }
public Quarters Quarter { get; set; }
public Int32 QuarterId { get; set; }
}
Controller
public JsonResult Months(Quarters q) {
var query = from c in _context.Months where c.QuarterId == q.QuarterId select c;
return Json(query);
}
JS
$("select[name=quarters]").change(function () {
var filterData = {
QuarterId: $("select[name=quarters]").val(),
Description: $("select[name=quarters]").text()
}
$.ajax({
type: "POST",
data: filterData,
url: "/Folder/Controller/Months",
success: function (data) {
for (var i = 0; i <= data.length; i++)
console.log("Months: " + data[i].Description);
}
})
})
Best Regards
data.length returns the length of an array, but index start from 0, so you want to replace <= with <.
for (var i = 0; i < data.length; i++)
console.log("Months: " + data[i].Description);

Categories