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

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

Related

I want to filter the serial in replace and return if it is used in repair

I tried this
$.ajax({
url: '/api/serials/index/',
method: 'GET',
data: {
reference_no: $(this).val()
},
success: function (response) {
let items_repairs = response[items_repairs];
let items_replaces = response[items_returns];
$('#repair_serial_no').empty().append('<option></option>');
let filteredResponse = response[0].filter(function(item) {
//Check if the serial is already used in the repair and return table
let usedInRepair = items_repairs.serial_no.indexOf(item.serial_no) !== -1;
let usedInReplaces = items_replaces.serial_no.indexOf(item.serial_no) !== -1;
if(!usedInRepair && !usedInReplaces) {
return item;
}
});
filteredResponse.forEach(item => {
let template = `<option value="${item.id}">${item.serial_no}</option>`;
$('#return_serial_no').append(template);
});
but when i click the click the select there is no serial showing
in my /api/serials/index/
public function index(Request $request)
{
$serials = SerialNumber::where('reference_no', $request->reference_no)->get(['id', 'serial_no']);
$items_repairs = ItemsRepair::all();
$items_returns = ItemsReturn::all();
$items_replaces = ItemsReplace::all();
return response()->json([$serials,$items_repairs,$items_returns,$items_replaces]);
I think you forgot to set the key as a string.
$.ajax({
...
success: function (response) {
let items_repairs = response['items_repairs'];
let items_replaces = response['items_returns'];
...
}

Parameter sent to ASP NET Core Controller from AJAX call is null if it's too large?

I have AJAX code in my page which calls an ASP.NET Core controller. The code sends a list of objects to the controller. When the list is short enough, say 8 objects, the fundFindingsGridRows parameter is properly set to the data, however, when longer, this parameter is null.
I have tried setting several things in my Startup.cs but nothing has worked. Is there some other setting that I can configure to get this to accept larger amounts of data? Is there another issue other than size at play here?
Startup.cs (pertinent code):
services.AddMvc(options =>
{
options.MaxModelBindingCollectionSize = 100000;
});
services.Configure<FormOptions>(options =>
{
options.ValueCountLimit = int.MaxValue;
options.ValueLengthLimit = int.MaxValue;
options.MultipartHeadersLengthLimit = int.MaxValue;
});
services.Configure<IISServerOptions>(options =>
{
options.MaxRequestBodySize = int.MaxValue;
});
Javascript AJAX code:
var DATA = new Array();
var grid = $("#V3FundFindingsByBuildingGrid").data("kendoGrid");
var dataTable = grid.dataSource;
$.each(grid.items(), function (index, item) {
var id = $(item).data('uid');
var dataItem = dataTable.getByUid(id);
var building = {};
building.PANumber = dataItem.PANumber,
building.employerNo = dataItem.employerNo,
building.billToEntityNo = dataItem.billToEntityNo,
building.accountNo = dataItem.AccountNo,
building.revisionDateExists = #Model.revisionDateExists.ToString().ToLower(),
building.settlement = false,
building.health = dataItem.Health,
building.pension = dataItem.Pension,
building.annuity = dataItem.Annuity,
building.legal = dataItem.Legal,
building.training = dataItem.Training,
building.joint = dataItem.Joint,
building.four01k = dataItem.Four01k,
building.healthInterest = dataItem.HealthInterest,
building.pensionInterest = dataItem.PensionInterest,
building.annuityInterest = dataItem.AnnuityInterest,
building.legalInterest = dataItem.LegalInterest,
building.trainingInterest = dataItem.TrainingInterest,
building.jointInterest = dataItem.JointInterest,
building.four01kInterest = dataItem.Four01kInterest
DATA.push(building);
});
var fundFindingsGridRows = JSON.stringify(DATA);
$.ajax({
type: "POST",
url: "/PayrollAudit/SaveFundFindings",
data: fundFindingsGridRows,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$('#FindingsByBuildingDiv').html(response);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
Controller Action:
[RequestSizeLimit(100_000_000)]
public IActionResult SaveFundFindings([FromBody]List<FundFindingsGridRow> fundFindingsGridRows)
{...}
Data from the Header:
Parsed payload snippet:
So I found away to solve this issue. What I did was to not send the data to the controller as JSON, and instead of as an array of objects. I also removed the contentType and dataType settings from the AJAX call, and changed the data setting:
var DATA = new Array();
var grid = $("#V3FundFindingsByBuildingGrid").data("kendoGrid");
var dataTable = grid.dataSource;
$.each(grid.items(), function (index, item) {
var id = $(item).data('uid');
var dataItem = dataTable.getByUid(id);
var FundFindingsGridRow = {};
FundFindingsGridRow.PANumber = dataItem.PANumber,
FundFindingsGridRow.employerNo = dataItem.employerNo,
FundFindingsGridRow.billToEntityNo = dataItem.billToEntityNo,
FundFindingsGridRow.accountNo = dataItem.AccountNo,
FundFindingsGridRow.revisionDateExists = #Model.revisionDateExists.ToString().ToLower(),
FundFindingsGridRow.settlement = false,
FundFindingsGridRow.health = dataItem.Health,
FundFindingsGridRow.pension = dataItem.Pension,
FundFindingsGridRow.annuity = dataItem.Annuity,
FundFindingsGridRow.legal = dataItem.Legal,
FundFindingsGridRow.training = dataItem.Training,
FundFindingsGridRow.joint = dataItem.Joint,
FundFindingsGridRow.four01k = dataItem.Four01k,
FundFindingsGridRow.healthInterest = dataItem.HealthInterest,
FundFindingsGridRow.pensionInterest = dataItem.PensionInterest,
FundFindingsGridRow.annuityInterest = dataItem.AnnuityInterest,
FundFindingsGridRow.legalInterest = dataItem.LegalInterest,
FundFindingsGridRow.trainingInterest = dataItem.TrainingInterest,
FundFindingsGridRow.jointInterest = dataItem.JointInterest,
FundFindingsGridRow.four01kInterest = dataItem.Four01kInterest
DATA.push(FundFindingsGridRow);
});
$.ajax({
type: "POST",
url: "/PayrollAudit/SaveFundFindings",
data: { 'fundFindingsGridRows': DATA },
success: function (response) {
$('#FindingsByBuildingDiv').html(response);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
Not sure what the issue was with the JSON. If someone can let me know, I'd appreciate it in case I run across an instance where JSON is required in the future!
Below is a work demo that can send the data to the controller as JSON, you can refer to it.
Student:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Name2 { get; set; }
public string Name3 { get; set; }
public string Name4 { get; set; }
public string Name5 { get; set; }
public string Name6 { get; set; }
public string Name7 { get; set; }
public string Name8 { get; set; }
public string Name9 { get; set; }
public string Name10 { get; set; }
}
HomeController:
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index([FromBody] List<Student> student)
{
return View();
}
}
Index view:
<button onclick="postdata1()">submit(jsondata)</button>
#section scripts{
<script type="text/javascript">
function postdata1() {
var a = new Array();
for (var i = 0; i < 100000; i++) {
var indexViewModel = {};
indexViewModel.Id = i;
indexViewModel.Name = "name" + i;
indexViewModel.Name2 = "name2" + i;
indexViewModel.Name3 = "name3" + i;
indexViewModel.Name4 = "name4" + i;
indexViewModel.Name5 = "name5" + i;
indexViewModel.Name6 = "name6" + i;
indexViewModel.Name7 = "name7" + i;
indexViewModel.Name8 = "name8" + i;
indexViewModel.Name9 = "name9" + i;
indexViewModel.Name10 ="name10" + i;
a.push(indexViewModel);
}
var data = JSON.stringify(a);
$.ajax({
type: "POST",
url: '/home/Index',
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
}).done(function (data) {
});
}
</script>
}
result:

System.Data.Entity.DynamicProxies

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?

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

Categories

Resources