Send Variable from AJAX table to ASP.NET MVC Controller - asp.net

I understand the topic is relatively common, but I've spent a LONG time trying to solve this issue with pre-existing posts and I have come up with no luck to solving my issue.
I have got a Homepage with a small database of "Safes", When a user clicks on one of the safes, it should take them to the "Items" Database view and show ONLY the items of the safe they clicked on. However, instead it shows no results? (I have got the items table to display ALL results, so I know it is not an issue with the database). More baffling is that the "data" I wish to use as the filter does show properly in the URL, so that should be fine too?
Any help would be MUCH appreciated... Thanks in advance peeps! :)
$(document).ready(function () {
var oTable = $('#CBR').DataTable({
"ajax": {
"url": '/Home/GetSafe',
"type": "get",
"datatype": "json"
},
"columns": [
{ "data": "Safe_ID", "autoWidth": true },
{ "data": "Department_ID", "autoWidth": true },
{
"data": "Safe_ID", "width": "50px", "render": function (selectedSafe) {
$.ajax({
url: '/Home/GetSafeItems',
dataType: "json",
data: { selectedSafe: selectedSafe },
type: "GET",
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert(selectedSafe);
}
});
return 'Open Safe';
}
}
]
})
HOMEPAGE VIEW (above)
public ActionResult GetSafeItems(string selectedSafe)
{
using (CBREntities2 dc = new CBREntities2())
{
var safeItem = dc.Items.Where(a => a.Safe_ID == selectedSafe).Select(s => new {
Serial_Number = s.Serial_Number,
Safe_ID = s.Safe_ID,
Date_of_Entry = s.Date_of_Entry,
Title_subject = s.Title_subject,
Document_Type = s.Document_Type,
Sender_of_Originator = s.Sender_of_Originator,
Reference_Number = s.Reference_Number,
Protective_Marking = s.Protective_Marking,
Number_recieved_produced = s.Number_recieved_produced,
copy_number = s.copy_number,
Status = s.Status,
Same_day_Loan = s.Same_day_Loan
}).ToList();
// var safeItems = dc.Items.Where(a => a.Safe_ID).Select(s => new { Safe_ID = s.Safe_ID, Department_ID = s.Department_ID, User_ID = s.User_ID }).ToList();
return Json(new { data = safeItem }, JsonRequestBehavior.AllowGet);
}
}
Controller (above)
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Items</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet"
href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" />
<link href="~/Content/themes/base/jquery-ui.min.css" rel="stylesheet" />
</head>
<body>
<div style="width:90%; margin:0 auto" class="tablecontainer">
<a class="popup btn btn-primary" href="/home/SaveItem/0" style="margin-
bottom:20px; margin-top:20px">Add new Item </a>
<table id="CBR-Item">
<thead>
<tr>
<th>Serial Number</th>
<th>Safe ID</th>
<th>Date of Entry</th>
<th>Title/Subject</th>
<th>Document type</th>
<th>Sender of Originator</th>
<th>Reference Number</th>
<th>Protective Marking</th>
<th>Number recieved/produced</th>
<th>Copy number</th>
<th>Status</th>
<th>Same-Day Loan</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
</table>
</div>
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script>
$(document).ready(function () {
var oTable = $('#CBR-Item').DataTable({
"ajax": {
"url": '/Home/GetSafeItems',
"type": "get",
"datatype": "json"
},
"columns": [
{ "data": "Serial_Number", "autoWidth": true },
{ "data": "Safe_ID", "autoWidth": true },
{ "data": "Date_of_Entry", "autoWidth": true },
{ "data": "Title_subject", "autoWidth": true },
{ "data": "Document_Type", "autoWidth": true },
{ "data": "Sender_of_Originator", "autoWidth": true },
{ "data": "Reference_Number", "autoWidth": true },
{ "data": "Protective_Marking", "autoWidth": true },
{ "data": "Number_recieved_produced", "autoWidth": true },
{ "data": "copy_number", "autoWidth": true },
{ "data": "Status", "autoWidth": true },
{ "data": "Same_day_Loan", "autoWidth": true },
{
"data": "Serial_Number", "width": "50px", "render": function (data) {
return '<a class="popup" href="/home/SaveItem/' + data + '">Edit</a>';
}
},
{
"data": "Serial_Number", "width": "50px", "render": function (data) {
return '<a class="popup" href="/home/DeleteItem/' + data + '">Delete</a>';
}
}
]
})
$('.tablecontainer').on('click', 'a.popup', function (e) {
e.preventDefault();
OpenPopup($(this).attr('href'));
})
function OpenPopup(pageUrl) {
var $pageContent = $('<div/>');
$pageContent.load(pageUrl, function () {
$('#popupForm', $pageContent).removeData('validator');
$('#popupForm', $pageContent).removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse('form');
});
$dialog = $('<div class="popupWindow" style="overflow:auto"></div>')
.html($pageContent)
.dialog({
draggable: false,
autoOpen: false,
resizable: false,
model: true,
title: 'Popup Dialog',
height: 550,
width: 600,
close: function () {
$dialog.dialog('destroy').remove();
}
})
$('.popupWindow').on('submit', '#popupForm', function (e) {
var url = $('#popupForm')[0].action;
$.ajax({
type: "POST",
url: url,
data: $('#popupForm').serialize(),
success: function (data) {
if (data.status) {
$dialog.dialog('close');
oTable.ajax.reload();
}
}
})
e.preventDefault();
})
$dialog.dialog('open');
}
})
</script>
Main safe View (above)
I have not inlcuded the safe view as that element works usually without the filter and is calling to the controller method. But can upload if needed.
Amendment: I have almost solved the post issue... but the post won't actually reach the controller (it just keeps tripping the error value in the code Below)
{
"data": "Safe_ID", "width": "50px", "render": function (data) {
return '<a class="safeLink" href="/home/safeItems/' + data + '">Open Safe</a>';
// return { selectedSafe: selectedSafe }
}
}
]
})
$('.tablecontainer').on('click', 'a.safeLink', function (e) {
e.preventDefault();
var whatWhat = "SEC-1000";
var selectedSafeZZ = { theSafe: whatWhat };
$.ajax({
url: '/Home/GetSafeItems',
data: JSON.stringify(selectedSafeZZ),
contentType: "application/json; charset=utf-8;",
type: "POST",
success: function (data) {
alert(data);
},
error: function (xhr) {
alert("Boohooo");
}
});

Your ajax call has nothing to do with anchor tag link. So do you have any method in home controller which returns data to view like viewresult.?
Can you paste your complete controllers code

Related

Ajax and error cannot read properties of undefined

So I am trying to get some data from a table using ajax but this error keeps popping up and I know its related to parameters but I have none of the parameters it says are wrong anyone got any ideas?
I am working in asp.net 6 and am trying to get the data to a controller.
I am currently working in C# and ajax
(function () {
"use strict"
window.onload = function () {
//Reference the DropDownList.
var ddlYears = document.getElementById("ddlYears");
//Determine the Current Year.
var currentYear = (new Date()).getFullYear() + 10;
var less = (new Date()).getFullYear() - 10;
//Loop and add the Year values to DropDownList.
for (var i = less; i <= currentYear; i++) {
var option = document.createElement("OPTION");
option.innerHTML = i;
option.value = i;
ddlYears.appendChild(option);
}
};
var ScopeTable;
$(document).ready(function () {
ScopeTable = $("#tblScopeView").DataTable({
dom: "Bfrtip",
paging: true,
pagingType: "full_numbers",
buttons: [
"csvHtml5"
],
columns: [
{ data: 'WBS' },
{ data: 'Title' },
{ data: 'Rev' },
{ data: 'ScopeStatus' },
{ data: 'BCP' },
{ data: 'BCPApprovalDate' },
{ data: 'Manager' },
{ data: 'ProjectControlManager' },
{ data: 'ProjectControlEngineer' },
{
mRender: function (data, type, row) {
return "<i class='fa fa-edit btnAddEditScope'></i><span> Edit</span >"
},
class: "btnAddEditScope table-button",
orderable: false
},
{
mRender: function (data, type, row) {
return "<i class='fa fa-trash btnDeleteRow'></i><span> Delete</span >"
},
orderable: false,
class: "table-button"
}
],
createdRow: function (row, data, index) {
$(row).attr("data-id", data.WBSNumber);
$(row).attr("data-month", data.FiscalMonth);
$(row).attr("data-year", data.FiscalYear);
}
});
$(document).on("click", ".btnAddEditScope", btnAddEditScope_click);
$("#spnrSave").hide();
});
function btnAddEditScope_click() {
console.log("button clicked")
$.ajax({
url: "Scope/AddEditScope",
type: "GET",
success: function () {
$("#vw_AddEditScope").modal("show");
}
});
}
}());
Error that is being posted
Figured it out just had do adjust my ajax and it worked fine. The tutorial I found is here https://datatables.net/examples/api/multi_filter.html
var ScopeTable;
$(document).ready(function (e) {
ScopeTable = $("#tblScopeView").DataTable({
dom: "Bfrtip",
paging: true,
pagingType: "full_numbers",
buttons: [
"csvHtml5"
],
columns: [
{ data: 'WBS' },
{ data: 'Title' },
{ data: 'Rev' },
{ data: 'ScopeStatus' },
{ data: 'BCP' },
{ data: 'BCPApprovalDate' },
{ data: 'Manager' },
{ data: 'ProjectControlManager' },
{ data: 'ProjectControlEngineer' },
{
mRender: function (data, type, row) {
return "<i class='fa fa-edit btnAddEditScope'></i><span> Edit</span >"
},
class: "btnAddEditScope table-button",
orderable: false
}, {
mRender: function (data, type, row) {
return "<i class='fa fa-trash btnDeleteRow'></i><span> Delete</span >"
},
orderable: false,
class: "table-button"
},
],
createdRow: function (row, data, index) {
$(row).attr("data-id", data.WBSNumber);
$(row).attr("data-month", data.FiscalMonth);
$(row).attr("data-year", data.FiscalYear);
},
error: function (e) {
console.log(e);
}
});
$('#tblScopeView tfoot th').each(function () {
var title = $("#tblScopeView").eq($(this).index()).text();
$(this).html('<input type="text" class="form-control" placeholder="Search ' + title + '" />');
ScopeTable.columns().every(function () {
var dataTableColumn = this;
$(this.footer()).find('input').on('keyup change', function () {
dataTableColumn.search(this.value).draw();
});
});
});
$("#spnrSave").hide();
$(document).on("click", ".btnAddEditScope", btnAddEditScope_click);
});

method for add and update data from popup

I have a pop up form from which new data can be added or old data can be updated.
But I don't know how to write method for this condition. I mean in the case of new data entry I don't need the Id but in case of edit I need the Id attribute. The controller name is Vehicle.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddorEdit([Bind(Include = "Id,VehicleType,Amount,RenewPeriod,Status")] Vehicle vehicle)
{
vehicle.RegisteredDate = DateTime.Now;
vehicle.RegisteredBy = "admin";
if (ModelState.IsValid)
{
db.Vehicle.Add(vehicle);
db.SaveChanges();
}
return Json(new { success = true, message = "Saved Successfully" }, JsonRequestBehavior.AllowGet);
}
The jquery code of index page from where pop up is called ::
<a class="btn btn-success" style="margin-bottom:10px;" onclick="PopupForm('#Url.Action("AddorEdit", "Vehicles")')"><i class="fa fa-plus"></i> Add New</a>
<script>
var Popup, dataTable;
$(document).ready(function () {
dataTable = $("#tbl_vehicle").DataTable({
"ajax":{
"url": "/Vehicles/GetVehicle",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "VehicleType" },
{ "data": "Amount" },
{ "data": "RenewPeriod" },
{ "data": "RegisteredDate" },
{ "data": "RegisteredBy" },
{ "data": "Status" },
{ "data": "ModifiedBy" },
{ "data": "ModifiedDate" }
],
"language": {
"emptyTable" : "No data available, please click on <b>Add</b> button"
}
});
});
function PopupForm(url) {
var formDiv = $('<div/>');
$.get(url).done(function (response) {
formDiv.html(response);
Popup = formDiv.dialog({
autoOpen: true,
resizable: false,
title: 'fill details',
height: 500,
width: 700,
close: function () {
Popup.dialog('destroy').remove();
}
});
});
}
function SubmitForm(form) {
alert("testing....");
$.ajax({
type: "POST",
url: form.action,
data: $(form).serialize(),
success: function (date) {
if(data.success)
{
Popup.dialog('close');
dataTable.ajax.reload();
}
}
});
return false;
}
</script>
An easy way to handle this by making id as a HiddenField so when ever user post data to the server you can query the id field.
whether it has value or not and decide which operation you should perform i.e. Add operation if id is null/empty and Edit Operation if Id has the value.
Please use below code section for reference :
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddorEdit([Bind(Include = "Id,VehicleType,Amount,RenewPeriod,Status")] Vehicle vehicle)
{
if (ModelState.IsValid)
{
if(vehicle.Id <= 0)
{
vehicle.RegisteredDate = DateTime.Now;
vehicle.RegisteredBy = "admin";
db.Vehicle.Add(vehicle);
}
else
{
db.Entry(vehicle).State = EntityState.Modified;
//perform more checks if you want
}
db.SaveChanges();
}
return Json(new { success = true, message = "Saved Successfully" }, JsonRequestBehavior.AllowGet);
}
You can achieve it by this simple way
if (ModelState.IsValid)
{
if(vehicle.Id <= 0)
{
vehicle.RegisteredDate = DateTime.Now;
vehicle.RegisteredBy = "admin";
db.Vehicle.Add(vehicle);
}
else
db.Entry(vehicle).State = EntityState.Modified;
db.SaveChanges();
}

Need to transform Razor code on ASPX code

So, I need help to make this code work as ASPX, can anyone help me?
I know it,s just a few parts to be changed, but i don't know how to do it...
Or if Any one know hot to achive the same result other way this would be very helpfull.
I already try do it myself but got no luck doing so.. =/
So, I need help to make this code work as ASPX, can anyone help me?
I know it,s just a few parts to be changed, but i don't know how to do it...
Or if Any one know hot to achive the same result other way this would be very helpfull.
I already try do it myself but got no luck doing so.. =/
#{
ViewBag.Title = "Employee List";
}
<a class="btn btn-success" style="margin-bottom:10px"
onclick="PopupForm('#Url.Action("AddOrEdit","Employee")')"><i class="fa fa-
plus"></i> Add New</a>
<table id="employeeTable" class="table table-striped table-bordered"
style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Salary</th>
<th></th>
</tr>
</thead>
</table>
<link href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
#section scripts{
<script src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script>
<script>
var Popup, dataTable;
$(document).ready(function () {
dataTable = $("#employeeTable").DataTable({
"ajax": {
"url": "/Employee/GetData",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "Name" },
{ "data": "Position" },
{ "data": "Office" },
{ "data": "Age" },
{ "data": "Salary" },
{"data":"EmployeeID" , "render" : function (data) {
return "<a class='btn btn-default btn-sm' onclick=PopupForm('#Url.Action("AddOrEdit","Employee")/" + data + "')><i class='fa fa-pencil'></i> Edit</a><a class='btn btn-danger btn-sm' style='margin-left:5px' onclick=Delete("+data+")><i class='fa fa-trash'></i> Delete</a>";
},
"orderable": false,
"searchable":false,
"width":"150px"
}
],
"language": {
"emptyTable" : "No data found, Please click on <b>Add New</b> Button"
}
});
});
function PopupForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function (response) {
formDiv.html(response);
Popup = formDiv.dialog({
autoOpen: true,
resizable: false,
title: 'Fill Employee Details',
height: 500,
width: 700,
close: function () {
Popup.dialog('destroy').remove();
}
});
});
}
function SubmitForm(form) {
$.validator.unobtrusive.parse(form);
if($(form).valid()){
$.ajax({
type : "POST",
url : form.action,
data : $(form).serialize(),
success : function (data) {
if(data.success)
{
Popup.dialog('close');
dataTable.ajax.reload();
$.notify(data.message,{
globalPosition :"top center",
className : "success"
})
}
}
});
}
return false;
}
function Delete(id) {
if(confirm('Are You Sure to Delete this Employee Record ?'))
{
$.ajax({
type: "POST",
url: '#Url.Action("Delete","Employee")/' + id,
success: function (data) {
if (data.success)
{
dataTable.ajax.reload();
$.notify(data.message, {
globalPosition: "top center",
className: "success"
})
}
}
});
}
}
</script>
}

Why highchart not show me in asp.net?

I'm beginner in asp.net and highchart control,want to use highchart control in my web application web form,for that purpose read this tutorial:
this tutorial
and write this web service in my project:
public class cityPopulation
{
public string city_name { get; set; }
public int population { get; set; }
public string id { get; set; }
}
[WebMethod]
public List<cityPopulation> getCityPopulation(List<string> pData)
{
List<cityPopulation> p = new List<cityPopulation>();
cityPopulation cpData = new cityPopulation();
cpData.city_name = "tabriz";
cpData.population = 100;
p.Add(cpData);
return p;
}
that web service name is this:
WebService1.asmx
and in my web form write this script :
<script type="text/javascript">
function drawPieChart(seriesData) {
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Population percentage city wise'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
name: "Brands",
colorByPoint: true,
data: seriesData
}]
});
}
$("#btnCreatePieChart").on('click', function (e) {
var pData = [];
pData[0] = $("#ddlyear").val();
var jsonData = JSON.stringify({ pData: pData });
$.ajax({
type: "POST",
url: "WebService1.asmx/getCityPopulation",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess_,
error: OnErrorCall_
});
function OnSuccess_(response) {
var aData = response.d;
var arr = []
$.map(aData, function (item, index) {
var i = [item.city_name, item.population];
var obj = {};
obj.name = item.city_name;
obj.y = item.population;
arr.push(obj);
});
var myJsonString = JSON.stringify(arr);
var jsonArray = JSON.parse(JSON.stringify(arr));
drawPieChart(jsonArray);
}
function OnErrorCall_(response) {
alert("Whoops something went wrong!");
}
e.preventDefault();
});
//*
</script>
before that script write this code:
<script src="Scripts/jquery-2.2.3.min.js"></script>
<script src="Scripts/Highcharts-4.0.1/js/highcharts.js"></script>
and write this html code:
<select id="ddlyear">
<option>2010</option>
<option>2011</option>
<option>2012</option>
<option>2013</option>
<option>2014</option>
<option>2015</option>
</select>
<button id="btnCreatePieChart">Show </button>
<br />
<div>
<div id="container" style="width: 500px; height: 500px"></div>
</div>
but when i run project and fire the button,can not see anything,and chart not show to me,what happen?is my code incorrect?how can i solve that problem?thanks.
i think ajax can not call the web service!

ASP.NET and jQuery Remote Validation: Validation function not called

I have this client function:
$(document).ready(function() {
var validate = $("#<%=Page.Form.ClientID%>").validate({
errorElement: 'span',
rules: {
<%=txtMemberShipNumber.ClientID %> : {
required: true,
remote: function () {
return {
url: "/TestForm.aspx/IsMembershipNumberValid",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ value: $('#<%=txtMemberShipNumber.ClientID %>').val() }),
dataFilter: function (data) {
var msg = JSON.parse(data);
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
}
}
},
},
},
messages: {
<%=txtMemberShipNumber.ClientID %> : {
required: "Account number is Required",
remote: "Invalid",
},
},
onkeyup:false,
onblur: true,
onfocusout: function (element) { $(element).valid() }
});
})
... that validates this control:
<input name="ctl00$MainContent$txtMemberShipNumber" type="text" id="MainContent_txtMemberShipNumber" class="textboxStyle" placeholder="Membership Number" />
The problem is the validation code is never called. I've tested it in Firefox and Chrome.
Am I missing something?
I figured it out.
Instead of
<%=txtMemberShipNumber.ClientID %> : {
... you should use
<%=txtMemberShipNumber.UniqueID%> : {

Resources