System.Data.Entity.DynamicProxies - javascript

I tried this code in my controller Can any one show me the solution:
public JsonResult GetMembers(Member member)
{
//var list = repository.GetAll().Select(x => new ViewModel.MemberView
//{
// Memberid = x.id,
// Name = x.name,
// EmailAddress = x.Email,
// Role = x.role.rolename,
// ReportingRoleId = Convert.ToInt32(x.reportingroleid)
//});
var list = repository.GetAll();
return Json(list , JsonRequestBehavior.AllowGet);
}
javascript function
<script type="text/javascript">
debugger;
alert('first');
google.load("visualization", "1", {packages:["orgchart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
type: "POST",
url: "/Organization/GetMembers",
data :'{member:"+JSON.stringify(member)+"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("Member Name"+data);
//var data = new google.visualization.DataTable();
//data.addColumn('string','name');
//data.addColumn('string', 'role');
//data.addColumn('string', 'ToolTip');
//for (var i = 0; i < r.length; i++) {
// var memberId = r[i][0];
// var Name = r[i][1];
// var role= r[i][2];
// var reportingrole= r[i][3] != null ? r[i][3].toString() : '';
// data.addRows([[{
// v: employeeId,
// f: Name + '<div>(<span>' + role + '</span>)</div><img src = "/Pictures/' + memberId + '.jpg" />'
// }, reportingrole, role]]);
//}
// var chart = new google.visualization.OrgChart($("#chart")[0]);
// chart.draw(data, { allowHtml: true });
},
failure: function (r) {
alert(r);
},
error: function (r) {
alert(r);
}
});
}
It was Error
A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.NewProjects_A3B55EADDAEF6C59245BBD2495E29ECFE10B583596DB24AADF23A4990342D104'.

I had the same error, but this is worked for me, this is when you want to select
public MyDbContext() : base("name=MyDbContext"){this.Configuration.ProxyCreationEnabled = false;}
before you call yout table use this this.Configuration.ProxyCreationEnabled = false;

You should convert your data to list before returning it. EF return proxies for lazy loading and stuff. Try below code.
var list = repository.GetAll().ToList();
Also Look at this.
Why is EF returning a proxy class instead of the actual entity?

Related

View is not passing the model to controller - ASP.Net MVC

This is a basic passing of values from view to controller, but this does not seek to work.When I click the update button that functions to update the record in the database, the values from view, does not correctly pass the values to controller. Upon putting debugger in the javascript, the each variables were able to correctly got its values and evn the object where they are stored.
What could possible the reason for this problem?
here's the button onclick event code in Javascript.
$('#updatePrescription').click(function () {
debugger;
ValidateFields();
var drugListIsEmpty = CheckDrugList();
var error = $(".text-danger").length;
if (error == 0 && !drugListIsEmpty) {
debugger;
var prescription = [];
var template = {};
template.templateName = $("#prescriptionTemplateName").val();
template.templateTypeId = $('input[name=templateTypeId]:checked').val();
template.prescriptionTemplateItemList = [];
template.instructionId = $('.instruction').val();
template.frequencyId = $('.frequency').val();
template.day = $('.inputDays').val();
template.quantity = $('.inputQuantity').val();
template.dispenseLocationId = $('.selectDispenseLocation').val();
template.statusId = $('.status').val();
//template.categoryId = $('.templateCategory').filter(":visible").last().val();
template.templateId = $('#prescriptionTemplateId').val();
//if (template.categoryId == null) {
// template.categoryId = 0;
//}
var x = 0;
$('#tblPrescriptionSaveTemplateBody tr').each(function (key, value) {
debugger;
var row = $(this).closest('tr');
var next_row = $(row).next();
var drugId = $(value).find('.drugId').val();
var dosage = $(value).find('.inputDosage').val();
var dosageUnitId = $(value).find('.selectUnitId').val();
var statusId = "41";
var remarks = $(value).find('.inputDescription').val();
var groupId = $(value).find('.inputGroupNo').val();
var unit = $(value).find('.selectUnitId').val();
var prescriptionTemplateItemId = $(value).find('.prescriptionTemplateItemId').val();
x++;
var obj = {
// templateId: prescriptionTemplateId,
prescriptionTemplateId: template.templateId,
prescriptionTemplateItemId: prescriptionTemplateItemId,
drugId: drugId,
dosage: dosage,
dosageUnitId: dosageUnitId,
instructionId: template.instructionId,
frequencyId: template.frequencyId,
day: template.day,
quanitity: template.quantity,
unit: unit,
remarks: remarks,
dispenseLocationId: template.dispenseLocationId,
groupId: groupId,
statusId: template.statusId
}
template.prescriptionTemplateItemList.push(obj);
//prescription.push(obj)
})
$.ajax({
type: 'POST',
url: '/WestMedicinePrescriptionTemplate/UpdateTemplate',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(template),
success: function (data) {
ShowNotificationMessage(data.notification);
window.location.href = '/WestMedicinePrescriptionTemplate/Index';
}
});
}
});
This is expected to pass the result of model in parameter "newtemplate" in the controller, but it results to null
public ActionResult UpdateTemplate([FromBody] PrescriptionTemplateVM newtemplate)
{
int empId = Convert.ToInt32(HttpContext.Session.GetInt32("EmployeeId"));
var notif = "Update Failed.";
try
{
if (ModelState.IsValid)
{
bool updateSuccessful = _prescription.UpdatePrescriptionTemplateAndItems(newtemplate, empId);
if (updateSuccessful)
{
notif = "Update Successful.";
}
}
}
catch (Exception ex)
{
notif = ex.Message;
}
return Json(new { notification = notif });
}
What could be the problem in the code
do like this:
[HttpPost]
public ActionResult UpdateTemplate(PrescriptionTemplateVM newtemplate)
You need to make sure that you are using the same variables names that you defined in PrescriptionTemplateVM
and dont convert the data to Json. do like this:
$.ajax({
type: 'POST',
url: '/WestMedicinePrescriptionTemplate/UpdateTemplate',
dataType: 'json',
contentType: 'application/json',
data: {newtemplate: template},
success: function (data) {
ShowNotificationMessage(data.notification);
window.location.href =
'/WestMedicinePrescriptionTemplate/Index';
}
});

Iterate over array items and check property value

function GetViewModelData() {
var RDcViewModel = [];
var recordId = $.trim($("#recordId").val());
for (i = 1; i <= rowCount; i++) {
var item1 = $.trim($("#item1" + i).val()) == '' ? 0 : parseInt($("#item1" + i).val());
var item2 = $.trim($("#item2" + i).val()) == '' ? 0 : parseInt($("#item2" + i).val());
var GrandTotal = (item1 + item2);
var rdtCViewModel = new ItemDetailsViewModel(0, item1, item2, GrandTotal);
RDcViewModel.push(rdtCViewModel);
}
var obj = new ReportViewModel(recordId, RDcViewModel);
var viewmodel = JSON.stringify(obj);
return viewmodel;
}
I have the above sample function that i'm using to iterate over html table rows and storing the row values in an array.
Once i have my array populated, i'm using below code snippet to post the data to my controller.
var PostData = function () {
$(".btnSubmit").click(function () {
var viewmodel = GetViewModelData();
//i want to check from here if viewmodel has any item(row) where GrandTotal is 0 (zero)
$.ajax({
async: true,
cache: false,
contentType: 'application/json; charset=utf-8',
data: viewmodel,
headers: GetRequestVerificationToken(),
type: 'POST',
url: '/' + virtualDirectory + '/Item/DataSave',
success: function (data) {
if (data == true) {
window.location.href = '/' + virtualDirectory + '/Destination/Index';
}
},
error: function (e) {
return false;
}
});
});
}
What i now want to do in my PostData function is to check if my "viewmodel" object contains any item(row) where "GrandTotal" is 0.
using JSON.parse(viewmodel), prepare object of type ReportViewModel with RDcViewModel JS array of type ItemDetailsViewModel and iterate over it to find if any grandtotal == 0 for ItemDetailsViewModel instances
var viewmodel = GetViewModelData(),
var obj = JSON.parse(viewmodel);
var bFoundZero=false;
$.each(obj.RDcViewModelArray, function(idx, elem){
if( elem.GrandTotal === 0 ) bFoundZero=true;
})
if( bFoundZero ) return 0;
As you have stringified it, now you have to parse it back if you want to access its keys and values:
var PostData = function() {
$(".btnSubmit").click(function() {
var viewmodel = GetViewModelData(),
viewObj = JSON.parse(viewmodel),
flag = false; // <-----parse it back here
viewObj.forEach(function(i, el){
flag = el.GrandTotal === 0;
return flag;
});
if(flag){ return false; } // <------ and stop it here.
$.ajax({
async: true,
cache: false,
contentType: 'application/json; charset=utf-8',
data: viewmodel,
headers: GetRequestVerificationToken(),
type: 'POST',
url: '/' + virtualDirectory + '/Item/DataSave',
success: function(data) {
if (data == true) {
window.location.href = '/' + virtualDirectory + '/Destination/Index';
}
},
error: function(e) {
return false;
}
});
});
}
There is no point iterating array again. Break the loop in GetViewModelData() and return false from that function. Then test it in PostData
Inside existing for loop:
var GrandTotal = (item1 + item2);
if(!GrandTotal){
return false;
}
Then in PostData()
var PostData = function () {
$(".btnSubmit").click(function () {
var viewmodel = GetViewModelData();
if(viewmodel === false){
alert('Missing total');
return; //don't proceed
}
/* your ajax */

Loading data from controller to chart Jquery/ MVC/ C#

I have the following controller code to return chart data to jquery.
UPDATE: I have modified the code as suggested, but still getting error.
public JsonResult GetLeaveDataForPieChart(int user_id)
{
List<EmployeeLeaveHeader> elh1 = new List<EmployeeLeaveHeader>();
List<ChartEvent> ch = new List<ChartEvent>();
elh1 = itlbg1.EmployeeLeaveHeaders.Where(f => f.Employee_ID == user_id).ToList();
foreach (var item in elh1)
{
ChartEvent ce = new ChartEvent();
ce.value = (item.leaveAvailable * 100).ToString();
ce.color = item.CompanyLeaves.LeaveTypes.color;
ce.highlight = "#ffffff";
ce.label = item.CompanyLeaves.LeaveTypes.typeDescription + " Leave Available";
ch.Add(ce);
ChartEvent ce1 = new ChartEvent();
ce1.value = (item.leaveTaken * 100).ToString();
ce1.color = item.CompanyLeaves.LeaveTypes.color_light;
ce1.highlight = "#ffffff";
ce1.label = item.CompanyLeaves.LeaveTypes.typeDescription + " Leave Taken";
ch.Add(ce1);
}
return Json(ch, JsonRequestBehavior.AllowGet);
}
I need to retrieve data in jquery so that it is in the required format to be passed to pie data.
(document).ready(function () {
user_id = $("#user_id_1").text();
$.ajax({
url: '/Leave/GetLeaveDataForPieChart/',
cache: false,
data: { user_id: user_id },
type: "GET",
datatype: "json",
success: function (data) {
alert(data);
var pieChartCanvas = $("#pieChart").get(0).getContext("2d");
var pieChart = new Chart(pieChartCanvas);
var PieData = $.each(data, function (idx, obj) {
var leave = new Object();
leave.value = obj.value;
leave.color = obj.color;
leave.highlight = obj.highlight;
leave.label = obj.label;
alert(leave);
return leave;
});
var pieOptions = {
//pie options..
};
pieChart.Doughnut(PieData, pieOptions);
}
});
Can anyone explain how to convert the json data to javascript object to be passed to the pie chart?
Here is how you parse JSON string into object.
var jsonObject = JSON.parse(jsonString);
here is how you use jquery to fetch the data and use it for your chart
$.ajax({
url: '/<Controller>/GetLeaveDataForPieChart/',
cache: false,
data: { user_id: <UserID> },
type: "GET",
success: function (data, textStatus, xmlHttpRequest) {
data = JSON.parse(data);
//....
//....
//Chart
//....
//....
//....
}
});

Url.Action Passing string array from View to Controller in MVC#

I have a method that returns an array (string[]) and I'm trying to pass this array of strings into an Action.Currently I can't pass my parameters. I am new in MVC3.
Pls let me know why I can't pass parameter to ActionResult..I already define ActionResult with Same parameter name..
thanks all in advance....
$('#export-button').click(function () {
var columnLength = $("#grid")[0].p.colNames.length;
var columnNames = "";
for (var i = 0; i < columnLength; i++) {
if ($("#grid")[0].p.colModel[i].hidden == false) {
columnNames = columnNames + $("#grid")[0].p.colModel[i].name + ',';
}
}
var Val1 = jQuery(txt_search1).val();
alert(Val1); alert(columnNames);
document.location = '#Url.Action("OrgDataExport","Search", new { Val1 = Val1 , columnNames = columnNames})';
});
Try this,
$('#export-button').click(function () {
var columnLength = $("#grid")[0].p.colNames.length;
// columnNames is an object now
var columnNames = {};
for (var i = 0; i < columnLength; i++) {
if ($("#grid")[0].p.colModel[i].hidden == false) {
columnNames[i] = $("#grid")[0].p.colModel[i].name;
}
}
var Val1 = jQuery(txt_search1).val();
document.location = "Home/Index/" + $.param({ Val1 = Val1 , columnNames = columnNames });
});
Your action that takes columnNames as a string array
public ActionResult Index(string val1, string[] columnNames)
{
// Your code
}
UPDATE:
If the URL becomes too big you can submit the values through form using POST method. If your view already have a form use that else create a dynamic one on the fly and submit the values through POST.
$('#export-button').click(function () {
var Val1 = jQuery(txt_search1).val();
$("#hidden-form").remove();
// create a form dynamically
var form = $('<form>')
.attr({ id: "hidden-form",
action: "/Home/Index",
method: "post",
style: "display: none;"
})
.appendTo("body");
// add the "Val1" as hidden field to the form.
$('<input>').attr({ name: "Val1 ", value: Val1, type: "hidden" }).appendTo(form);
var columnLength = $("#grid")[0].p.colNames.length;
// add the "columnNames" as hidden fields to the form
for (var i = 0; i < columnLength; i++) {
if ($("#grid")[0].p.colModel[i].hidden == false) {
var t = $("#grid")[0].p.colModel[i].name;
$('<input>').attr({ name: "columnNames", value: t, type: "hidden"
}).appendTo(form);
}
};
// submit the form
form.submit();
});
for (var i = 0; i < columnLength; i++) {
if ($("#grid")[0].p.colModel[i].hidden == false) {
columnNames = columnNames + $("#grid")[0].p.colModel[i].name + ',';
}
}
var Val1 = jQuery(txt_search1).val();
alert(Val1); alert(columnNames);
document.location = '#Url.Action("OrgDataExport","Search", new { Val1 = Val1 , columnNames = columnNames})';
Hi Louis,
Your are trying to access javascript varaibles Val1 and columnNames from the server side tag and it is not possible. For more details, please refer this URL.
You can do it by following way.
var jsonData = { val1 : Val1, columnNames : columnNames };
$.ajax({
type: "GET", //GET or POST or PUT or DELETE verb
url: "Home/Index", // Location of the service
data: jsonData,
contentType: "application/json; charset=utf-8", // content type sent to server
processdata: true, //True or False
success: function () {
alert("success")
}
});
On your controller side you have to write like
public ActionResult Index(string val1, string columnNames)
{
// Your code
}
You tagged JQuery-Ajax but i don't see any ajax attempt in the code example? So i am guessing you want to know an Ajax orientated solution. You're probably not using Zend Framework, but i hope this answers helps point you in the right direction to a solution.
From JS/Zend framework experience you could look at something like
$('#export-button').click(function () {
....
var actionUrl= "/controller/action/";
$.ajax({
url: actionUrl,
data: {
variable1: "OrgDataExport",
variable2: "Search",
Val1: Val1,
columnNames: columnNames
},
dataType: "json",
success: function(json) {
//do stuff
}
});
....
});
In the ZendFramework controller you can then grab the variables on the request:
$Val1 = $this->_request->getparam("Val1");

Javascript Function Returns Undefined JSON Object (But It's Not Undefined!)

I am trying to return a JSON object from a function using the JSON jQuery plugin (http://code.google.com/p/jquery-json/) but after returning the object from the function, it becomes undefined.
$(document).ready(function() {
var $calendar = $('#calendar');
$calendar.weekCalendar({
...
data : function(start, end, callback) {
var datas = getEventData();
alert(datas); // Undefined???
}
});
If I inspect the object before returning it, it is defined.
function getEventData() {
var dataString = "minDate="+ minDate/1000 + "&maxDate=" + maxDate/1000;
//alert(dataString);return false;
$.ajax({
type: "POST",
url: "busker_ops.php",
data: dataString,
dataType: "json",
success: function(data) {
if(data != null) {
var jsonArray = new Array();
var jsonObj = {};
for(var i = data.length - 1; i >= 0; --i) {
var o = data[i];
var set_id = o.set_id;
var start = o.startOrig;
var end = o.endOrig;
var title = o.title;
var deets = o.deets;
jsonObj =
{
"id":parseInt(set_id),
"start":$("#calendar").weekCalendar("formatDate", new Date(start), "c"),
"end":$("#calendar").weekCalendar("formatDate", new Date(end), "c"),
"title":title,
"body":deets
};
jsonArray[i] = jsonObj;
}
alert($.toJSON(jsonArray)); // Defined!
return ($.toJSON(jsonArray));
} else {
}
}
});
}
Any idea what I'm missing here?
function getEventData() {
function local() {
console.log(42);
return 42;
}
local();
}
Your missing the fact that the outer function returns undefined. And that's why your answer is undefined.
Your also doing asynchronous programming wrong. You want to use callbacks. There are probably 100s of duplicate questions about this exact problem.
Your getEventData() function returns nothing.
You are returning the JSON object from a callback function that's called asynchronously. Your call to $.ajax doesn't return anything, it just begins a background XMLHttpRequest and then immediately returns. When the request completes, it will call the success function if the HTTP request was successful. The success function returns to code internal in $.ajax, not to your function which originally called $.ajax.
I resolved this by using callbacks since AJAX is, after all. Once the data is retrieved it is assigned to a global variable in the callback and the calendar is refreshed using the global variable (datas).
$(document).ready(function() {
// Declare variables
var $calendar = $('#calendar');
datas = "";
set = 0;
// Retrieves event data
var events = {
getEvents : function(callback) {
var dataString = "minDate="+ minDate/1000 + "&maxDate=" + maxDate/1000;
$.ajax({
type: "POST",
url: "busker_ops.php",
data: dataString,
dataType: "json",
success: function(data) {
if(data != null) {
var jsonArray = new Array();
var jsonObj = {};
for(var i = data.length - 1; i >= 0; --i) {
var o = data[i];
var set_id = o.set_id;
var start = o.startOrig;
var end = o.endOrig;
var title = o.title;
var deets = o.deets;
jsonObj =
{
"id":parseInt(set_id),
"start":$("#calendar").weekCalendar("formatDate", new Date(start), "c"),
"end":$("#calendar").weekCalendar("formatDate", new Date(end), "c"),
"title":title,
"body":deets
};
jsonArray[i] = jsonObj;
}
//alert($.toJSON(jsonArray));
callback.call(this,jsonArray);
} else {
}
}
});
}
}
$calendar.weekCalendar({
data : function(start, end, callback) {
if(set == 1) {
callback(datas);
//alert(datas.events);
}
}
});
// Go get the event data
events.getEvents(function(evented) {
displayMessage("Retrieving the Lineup.");
datas = {
options : {},
events : evented
};
set = 1;
$calendar.weekCalendar("refresh");
});
});

Categories

Resources