Need to transform Razor code on ASPX code - asp.net

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

Related

Changing default button with Icon in Jquery DataTable is not working

I am using JQUERY DataTable. In that I am trying to change default button text with Icon. But except copy and Print other button icon is not changing. I am using Font Awesome To change text with icon. I have added Font Awesome : CDN also But its not appearing for csv, excel, pdf Why so? Am i missing any JQUERY references
Font Awesome CDN
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" />
To Change Text with Icon
initComplete: function () {
$('.buttons-copy').html('<i class="fa fa-copy" />')
$('.buttons-csv').html('<i class="fa fa-file-text-o" />')
$('.buttons-excel').html('<i class="fa fa-file-excel-o" />')
$('.buttons-pdf').html('<i class="fa fa-file-pdf-o" />')
$('.buttons-print').html('<i class="fa fa-print" />')
},
Complete JQuery DataTable
function LoadTableData() {
var params = {
PlantCode: $('#ddlPlant').val(), CostCenterCode: $("[id$='ddlCostCenter']").val(),
Status: $('input[name="Status"]:checked').val(), CompanyCode: $("[id$='ddlCompany']").val()
};
$.ajax({
url: 'UserService.asmx/Get_Data_Cost_Center_Master',
method: 'post',
data: JSON.stringify(params),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
$('#example').dataTable({
destroy: true,
data: data /*JSON.parse(data)*/,
columns: [
{
render: function (data, type, row, meta) {
return meta.row + meta.settings._iDisplayStart + 1;
}
},
{ 'data': 'Cost_Center', class: 'editable text' },
{ 'data': 'Plant', class: 'editable text' },
{ 'data': 'Status', class: 'editable text' }
],
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print'
],
initComplete: function () {
$('.buttons-copy').html('<i class="fa fa-copy" />')
$('.buttons-csv').html('<i class="fa fa-file-text-o" />')
$('.buttons-excel').html('<i class="fa fa-file-excel-o" />')
$('.buttons-pdf').html('<i class="fa fa-file-pdf-o" />')
$('.buttons-print').html('<i class="fa fa-print" />')
},
"searching": true,
"paging": true,
"info": true,
"language": {
"emptyTable": "No data available"
},
"fnRowCallback": function (nRow, aData, iDisplayIndex) {
$("td:first", nRow).html(iDisplayIndex + 1);
return nRow;
},
})
},
error: function (err) { // Added this event to capture the failed requests.
console.log(err.responseText);
}
});
};
Screenshot's
Where i am going Wrong? Kindly help me

Send Variable from AJAX table to ASP.NET MVC Controller

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

Datatables.net 2 Tabbed Table Ajax Get ASP.NET

I have a single Datatable configured using Datatables.net where I'm using bootstrap tabs to load a different dataset when a different tab is selected.
Ive configured it by referencing these two examples:
http://live.datatables.net/sozobucu/41/edit and http://www.tutorialrepublic.com/codelab.php?topic=bootstrap&file=create-dynamic-tabs-via-data-attribute.
When I run the application, I see that both Ajax Posts are submitted simultaneously and that the MVC controller switches back and forth line by line between the two ActionResults PopulateObjectATables and PopulateObjectBTables when I debug. I also notice that the JSON the app prepares to return looks correct at the time of the method return.
The issue is that the tab for ObjectA loads correctly and the JSON is returned from the server. However, I receive an error for ObjectB that refers me to http://datatables.net/tn/7 and in firebug I see that HTML is returned instead of JSON and a 502.3 Bad Gateway error is received.
As I see the correct JSON being prepared and both MVC ActionResults are written the same Ive ran out of things that I know to look for.
Scripts
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="~/lib/respond/dest/respond.min.js"></script>
<script src="~/lib/datatables/media/js/jquery.dataTables.js"></script>
<script src="http://cdn.datatables.net/responsive/1.0.6/js/dataTables.responsive.min.js"></script>
<script src="https://cdn.datatables.net/plug-ins/1.10.7/integration/bootstrap/3/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.9/css/dataTables.bootstrap.min.css" />
<link href="//cdn.datatables.net/responsive/1.0.6/css/dataTables.responsive.css" rel="stylesheet" />
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
#*<link rel="stylesheet" href="https://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css"/>*#
<link rel="stylesheet" href="~/css/site.css"/>
#*<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/jquery-ui.min.js"></script>*#
<script src="http://ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.8.3.js"></script>
<script src="~/lib/bootstrap-hover-dropdown/bootstrap-hover-dropdown.min.js"></script>
<script src="~/lib/angular/angular.js"></script>
<script src="~/lib/angular-datatables/dist/angular-datatables.js"></script>
View
#model NewInventory.ViewModels.ExampleAllViewModel
<p>
#Html.ActionLink("Create New", "Create")
</p>
<div class="container">
<div class="row">
<div class="well well-lg">
<ul class="nav nav-tabs">
<li class="active objectA-tab"><a data-toggle="tab" role="tab" data-target="#ObjectAData">Object A</a></li>
<li class="objectB-tab"><a data-toggle="tab" role="tab" data-target="#ObjectBData">Object B</a></li>
</ul>
<div class="tab-content">
<div id="ObjectAData" class="tab-pane fade in active" role="tabpanel">
<table id="ObjectATable1" class="table dt-responsive" cellspacing="0" style="width:100%">
<thead>
<tr>
<th>Example1</th>
<th>Example2</th>
<th>Example3</th>
<th>Example4</th>
<th>Example5</th>
<th>Example6</th>
<th>Example7</th>
<th>Example8</th>
<th>Example9</th>
</tr>
</thead>
</table>
</div>
<div id="ObjectBData" class="tab-pane fade in" role="tabpanel">
<table id="ObjectBTable1" class="table dt-responsive" cellspacing="0" style="width:100%">
<thead>
<tr>
<th>Example1</th>
<th>Example2</th>
<th>Example3</th>
<th>Example4</th>
<th>Example5</th>
<th>Example6</th>
<th>Example7</th>
<th>Example12</th>
<th>Example13</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
$('[data-toggle="popover"]').popover();
});
</script>
<script>
$('body').on('click', function (e) {
$('[data-toggle="popover"]').each(function () {
//the 'is' for buttons that trigger popups
//the 'has' for icons within a button that triggers a popup
if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
$(this).popover('hide');
}
});
});
</script>
<script>
$(document).ready(function () {
$("a[data-toggle=\"tab\"]").on("shown.bs.tab", function (e) {
console.log('show tab');
$($.fn.dataTable.tables(true)).DataTable()
.columns.adjust()
.responsive.recalc();
});
$("#ObjectATable1").dataTable({
"bServerSide": true,
"sAjaxSource": "PopulateObjectATables",
"bProcessing": true,
"ordering": false,
"paging": false,
"scrollY": "150px",
"searching": false,
"info": false,
"columns": [
{ "data": "Example1" },
{ "data": "Example2" },
{ "data": "Example3" },
{ "data": "Example4" },
{ "data": "Example5" },
{ "data": "Example6" },
{ "data": "Example7" },
{ "data": "Example8" },
{ "data": "Example9" }]
//"deferRender": true,
});
$("#ObjectBTable1").dataTable({
"bServerSide": true,
"sAjaxSource": "PopulateObjectBTables",
"bProcessing": true,
"ordering": false,
"paging": false,
"scrollY": "150px",
"searching": false,
"info": false,
//"deferRender": true,
"columns": [
{ "data": "Example1" },
{ "data": "Example2" },
{ "data": "Example3" },
{ "data": "Example4" },
{ "data": "Example5" },
{ "data": "Example6" },
{ "data": "Example7" },
{ "data": "Example12" },
{ "data": "Example13" }
]
});
});
</script>
MVC Controller ActionResults
public ActionResult PopulateObjectATables(jQueryDataTableParamModel param)
{
ExampleAllViewModel myVM = new ExampleAllViewModel();
List<ObjectA> ObjectAList = new List<ObjectA>(_repository.GetAllObjectA().ToList());
myVM.ListObjectA = ObjectAList;
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = myVM.ListObjectA.Count(),
iTotalDisplayRecords = myVM.ListObjectA.Count(),
aaData = myVM.ListObjectA
});
}
public ActionResult PopulateObjectBTables(jQueryDataTableParamModel param)
{
ExampleAllViewModel myVM = new ExampleAllViewModel();
List<ObjectB> ObjectBList = new List<ObjectB>(_repository.GetAllObjectB().ToList());
myVM.ListObjectB = ObjectBList;
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = myVM.ListObjectB.Count(),
iTotalDisplayRecords = myVM.ListObjectB.Count(),
aaData = myVM.ListObjectB
});
}
Although the errors themselves were not very descriptive or indicative of the root cause I was able to finally get the table ajax calls working once I realized the only difference between my two MVC ActionResult methods.
For ObjectB, inside of my repository method List<ObjectB> ObjectBList = new List<ObjectB>(_repository.GetAllObjectB().ToList()); I was eager loading a related entity along with ObjectB. However for ObjectA I was only returning ObjectA from the database.
Once I removed the include as shown below, the errors resolved.
return _context.ObjectB.ToList();
//return _context.ObjectB.Include(x => x.ObjectC).ToList();

Knockout asp.net - cannot read property of undefined

I'm really new to Knockout and have a question:
I try this example from the officail site.
So my html file is:
<head>
<script src="Scripts/jquery-2.1.1.min.js"></script>
<script src="Scripts/knockout-3.2.0.js"></script>
</head>
<body>
<div data-bind='simpleGrid: gridViewModel'> </div>
<button data-bind='click: addItem'>
Add item
</button>
<button data-bind='click: sortByName'>
Sort by name
</button>
<button data-bind='click: jumpToFirstPage, enable: gridViewModel.currentPageIndex'>
Jump to first page
</button>
<script src="FuseJS.js"></script>
</body>
</html>
and my js file is:
/// <reference path="Scripts/jquery-2.1.1.min.js" />
/// <reference path="Scripts/knockout-3.2.0.js" />
var initialData = [
{ name: "Well-Travelled Kitten", sales: 352, price: 75.95 },
{ name: "Speedy Coyote", sales: 89, price: 190.00 },
];
var PagedGridModel = function (items) {
this.items = ko.observableArray(items);
this.addItem = function () {
this.items.push({ name: "New item", sales: 0, price: 100 });
};
this.sortByName = function () {
this.items.sort(function (a, b) {
return a.name < b.name ? -1 : 1;
});
};
this.jumpToFirstPage = function () {
this.gridViewModel.currentPageIndex(0);
};
this.gridViewModel = new ko.simpleGrid.viewModel({
data: this.items,
columns: [
{ headerText: "Item Name", rowText: "name" },
{ headerText: "Sales Count", rowText: "sales" },
{ headerText: "Price", rowText: function (item) { return "$" + item.price.toFixed(2) } }
],
pageSize: 4
});
};
ko.applyBindings(new PagedGridModel(initialData));
What am I missing? I debug the code I saw this error
"UncauchType error: cannot read property 'viewModel' of undefined"
tnx
You are not using ko.applyBindings() anywhere.
ideally you need to do something like this.
ko.applyBindings(new PagedGridModel(initialData));

Knockout observables not binding and applyBindings firing twice

I had earlier asked this question here which worked in a html file. Now I am trying to put the same in the ASP.NET webform but does not seem to work.
What happens here the first time the page loads ajax call fires which I do not want except when the cursor is moved away from the text box
On Blur I have a popup window that I want to show the data returned from the ajax call. The data does not bind either. What am I doing wrong here.
My Javascript:
<script type="text/javascript">
var self = this;
function showPopUp() {
var cvr = document.getElementById("cover")
var dlg = document.getElementById("dialog")
var SName = document.getElementById("<%=txtSurname.ClientID%>").value
document.getElementById("txtSurnameSearch").value = SName
cvr.style.display = "block"
dlg.style.display = "block"
if (document.body.style.overflow = "hidden") {
cvr.style.width = "1024"
cvr.style.height = "100;"
}
this.SurnameViewModel(SName) //<= here I pass the surname to the ViewModel
}
function closePopUp(el) {
var cvr = document.getElementById("cover")
var dlg = document.getElementById(el)
cvr.style.display = "none"
dlg.style.display = "none"
document.body.style.overflowY = "scroll"
}
function SurnameViewModel(Surname) {
var self = this;
self.Surnames = ko.observableArray();
$.ajax({
crossDomain: true,
type: 'POST',
url: "http://localhost/GetSurnames/Name/ChurchID",
dataType: 'json',
data: { "Name":Surname, "ChurchID": "17" },
processdata: true,
success: function (result) {
alert(result.data);
ko.mapping.fromJSON(result.data, {}, self.Surnames);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Failure!");
alert(xhr.status);
alert(thrownError);
}
});
}
$(document).ready(function () {
ko.applyBindings(new SurnameViewModel());
});
</script>
My HTML
<!-- Grey Background -->
<div id="cover"></div>
<!-- Surname Popup -->
<div id="dialog" style="display:none">
My Dialog Content
<br /><input ID="txtSurnameSearch" type="text" />
<br /><input type="button" value="Submit" />
<br />[Close]
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre> //<= just shows the header
<table>
<thead>
<tr>
<th>ID</th>
<th>Family Name</th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: Surnames">
<tr>
<td data-bind="value: id"></td>
<td data-bind="value: homename"></td>
</tr>
</tbody>
</table>
</div>
TextBox where the onBlur is called:
<asp:TextBox ID="txtSurname" MaxLength="50" runat="server" Width="127px" class="txtboxes" placeholder="Last Name" onblur="showPopUp();" />
JSON Data returned by the ajax call
{"data":"[{\"id\":3,\"homename\":\"D\\u0027Costa\"}]"}
Edit 1:
If I hard code the values in the ajax call it seems to bind but still fires on page load
data: { "Name":"d", "ChurchID": "17" },
In your view model your Ajax call is inline, not inside a method, so as an instance of its contstructed your AJAX gets fired off. See this code, we create a global variable to hold the instance of your model and then wrap the AJAX call into its on function (method) in your JS. Then you can just call the method on your instance when you need to in your popup code.
var self = this;
var model = new SurnameViewModel();
function showPopUp() {
var cvr = document.getElementById("cover")
var dlg = document.getElementById("dialog")
var SName = document.getElementById("<%=txtSurname.ClientID%>").value
document.getElementById("txtSurnameSearch").value = SName
cvr.style.display = "block"
dlg.style.display = "block"
if (document.body.style.overflow = "hidden") {
cvr.style.width = "1024"
cvr.style.height = "100;"
}
model.GetSurname(SName) //<= here I pass the surname to the ViewModel
}
function closePopUp(el) {
var cvr = document.getElementById("cover")
var dlg = document.getElementById(el)
cvr.style.display = "none"
dlg.style.display = "none"
document.body.style.overflowY = "scroll"
}
function SurnameViewModel() {
var self = this;
self.Surnames = ko.observableArray();
self.GetSurname = function(Surname){
$.ajax({
crossDomain: true,
type: 'POST',
url: "http://localhost/GetSurnames/Name/ChurchID",
dataType: 'json',
data: { "Name":Surname, "ChurchID": "17" },
processdata: true,
success: function (result) {
alert(result.data);
ko.mapping.fromJSON(result.data, {}, self.Surnames);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Failure!");
alert(xhr.status);
alert(thrownError);
}
});
}
}
$(document).ready(function () {
ko.applyBindings(model);
});
</script>

Resources