Issues rendering DataTables.net in MVC partial view after adding JSON calls - c#

I'm trying to use datatables and jeditable for my project to render an editable table on the screen. This is displayed in a partial view that is called by the index. However, when I try to load it, it loads shows the html of the page on the screen instead of rendering it. Can someone tell me what I'm doing wrong to fix this?
Here is my partial view:
<script type="text/javascript" src="../../Scripts/jquery-1.9.1.js"></script>
<script type="text/javascript" src="../../Scripts/FixedColumns.min.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.dataTables.js"></script>
<script type ="text/javascript" src="../../Scripts/jquery.jeditable.mini.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
var oTable1 = $('#myDataTable').dataTable({
"bServerSide": true,
"sAjaxSource": '/Home/PartialView',
"fnDrawCallback": function () {
$('#myDataTable tbody td:nth-child(2)').editable('/Home/Write/', {
"callback": function (sValue, y) {
oTable1.fnDraw();
},
});
}
});
})
</script>
<table id ="myDataTable" class="display">
<thead>
<tr>
<th>Analysis ID</th>
<th>Name</th>
<th>Time</th>
<th>Sample Type</th>
<th>Grade</th>
<th>Product ID</th>
</thead>
<tbody>
</tbody>
</table>
Call to the partial view in my index:
#if(ViewBag.SearchKey != null)
{
#Html.Action("PartialAnalysis", "Home", (string)ViewBag.SearchKey)
{Html.RenderAction("PartialView", "Home", (string)ViewBag.SearchKey);}
}
My Controller:
public ActionResult PartialView(jQueryDataTableParamModel param, string Search)
{
PartialModel D = new PartialModel();
IEnumerable<PartialModel> model = D.SlagList;
D.ViewDataPull(Search);
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = D.List.Count(),
iTotalDisplayRecords = D.List.Count(),
aaData = D.List
},
JsonRequestBehavior.AllowGet);
}

Related

how to implement autocomplete functionality in search box in .net core mvc?

I tried to add autocomplete or suggestion functionality in search box of view, as when some one enter any character, any word containing that character shows as suggestion, but this not works. I followed different tutorials but not able to solve it. Please take a look and give me the direction.
Thnx in advance.
Controller
public async Task<IActionResult> dashboard(string sortOrder, string SearchString)
{
ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
var movies = from m in _context.Movie
select m;
if (!String.IsNullOrEmpty(SearchString))
{
movies = movies.Where(s => s.MovieName.Contains(SearchString));
}
switch (sortOrder)
{
case "name_desc":
movies = movies.OrderByDescending(s => s.MovieName);
break;
default:
movies = movies.OrderBy(s => s.MovieName);
break;
}
return View(await movies.AsNoTracking().ToListAsync());
}
public JsonResult AutoComplete(string prefix)
{
var customers = (from movie in this._context.Movie
where movie.MovieName.StartsWith(prefix)
select new
{
label = movie.MovieName,
val = movie.Id
}).ToList();
return Json(customers);
}
dashboard.cshtml
#model IEnumerable<WebApplication1.Models.Movie>
#{
ViewData["Title"] = "dashboard";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Dashboard</h1>
#using (Html.BeginForm())
{
<p>
Find by Movie Name: #Html.TextBox("SearchString")
<input type="hidden" id="hfCustomer" name="Id" />
<input type="submit" value="Search" />
</p>
}
<table class="table">
<thead>
<tr>
<th>
<a asp-action="dashboard" asp-route-sortOrder="#ViewData["NameSortParm"]">#Html.DisplayNameFor(model => model.MovieName)</a>
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.MovieName)
</td>
</tr>
}
</tbody>
</table>
<script type="text/javascript">
$(function () {
$("#txtMovie").autocomplete({
source: function (request, response) {
$.ajax({
url: '/Movies/AutoComplete/',
data: { "prefix": request.term },
type: "POST",
success: function (data) {
response($.map(data, function (item) {
return item;
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("#hfCustomer").val(i.item.val);
},
minLength: 1
});
});
</script>
I tried to add autocomplete or suggestion functionality in search box of view, as when some one enter any character, any word containing that character shows as suggestion, but this not works.
Find by Movie Name: #Html.TextBox("SearchString")
If you check the html source code of above TextBox in your browser, you would find it is rendered as below.
The value of id attribute is "SearchString", not "txtMovie". You can try to modify the code to use $("#SearchString") selector, like below.
$("#SearchString").autocomplete({
//...
//code logic here
//...
Test result with testing data
Note: please make sure you add references to required jquery libraries.
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

How to get Json result in to the table using angularJs

I'm trying to retrieve whole table in mvc5 using angularJS.
Data in Json result is being displayed but not in the table as I wanted.
I'm using mvc5 and angularjs(1.x) to retrive the data from sql server
Here's the Data Access Layer code:
public List<Employee> ShowAllEmployee()
{
List<Employee> prdList = userdb.Employees.ToList();
return prdList;
}
Here's the HomeController method:
public JsonResult AllEmployee()
{
repo = new Employee_DAL.EmpRepo();
var hotList = repo.ShowAllEmployee();
List<Models.Employee> mList = new List<Models.Employee>();
foreach (var hotl in hotList)
{
Models.Employee hotLocal = new Models.Employee();
hotLocal.EmployeeId = hotl.EmployeeId;
hotLocal.FirstName = hotl.FirstName;
hotLocal.LastName = hotl.LastName;
hotLocal.Designation = hotl.Designation;
//hotLocal.Description = hotl.Description;
hotLocal.Country = hotl.Country;
hotLocal.Gender = hotl.Gender;
//hotLocal.Rating = hotl.Rating;
//hotLocal.Email = hotl.Email;
mList.Add(hotLocal);
}
return Json(mList, JsonRequestBehavior.AllowGet);
}
Here's the script ( angular) code:
var myApp = angular.module('MyModule', []);
myApp.controller('DBcontroller', function ($scope, $http) {
$http.get('/Home/AllEmployee') // added an '/' along with deleting Controller portion
.then(function (response) {
$scope.students = response.data
})
})
Here's my view(cshtml):
#{
Layout = null;
}
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="~/Customs/angular.min.js"></script>
<script src="~/Customs/Scripts.js"></script>
<title>AllEmployee</title>
</head>
<body ng-app="myApp">
<div ng-controller="DBcontroller">
<table class="table-bordered">
<tr>
<th>Emp No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Designation</th>
<th>Country</th>
<th>Gender</th>
</tr>
<tr ng-repeat="e in students" #*ng-class-even="'even'" ng-class-odd="'odd'"*#>
<td>{{e.EmployeeId}}</td>
<td>{{e.FirstName}}</td>
<td>{{e.LastName}}</td>
<td>{{e.Designation}}</td>
<td>{{e.Country}}</td>
<td>{{e.Gender}}</td>
</tr>
</table>
</div>
</body>
</html>
I expect the jsonresult to be displayed in a table. Not directly like this in the browser.Screenshot of my current output

Gets Data in Json Format From AngularJs Controller

I am having a hard time with AngularJs. It works accordingly in some cases for me and when I try to change the template of the project, it doesn't work anymore. Here is the scenario - I have a controller in ASP.NET MVC that returns the list of products in Json format and finally I call this controller using AngularJs controller as follows:
C#:
public JsonResult GetProducts()
{
var result = (from c in db.Products
select new { c.ProductName, c.Price }).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
AngularJs:
var app = angular.module('app', []);
app.controller('ProductController', function ($scope, ProductService) {
$scope.Products = null;
ProductService.GetProducts().then(function (d) {
$scope.Products = d.data;
}, function () {
alert('Failed');
});
});
app.factory('ProductService', function ($http) {
var factory = {};
factory.GetProducts = function () {
return $http.get('/Product/GetProducts');
}
return factory;
});
In the UI, I've used the following:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Get Products</title>
<script src="~/Scripts/angular.js"></script>
<script src="../AngularFile/AddToCart.js"></script>
</head>
<body>
<div>
<h2>Get Products</h2>
<div ng-app="app" class="container">
<br /><br />
<br /><br />
<input type="text" ng-model="name" />
<h1>{{ name }}</h1>
<div ng-controller="ProductController">
<table class="table table-responsive" ng-repeat="m in Products">
<tr>
<td>{{ m.ProductName }}</td>
<td>{{ m.Price }}</td>
</tr>
</table>
</div>
</div>
</div>
</body>
</html>
The output I am getting is this:
I am not sure what I am doing wrong. In my earlier project, using the same code, it shows products properly but right now, I am getting data in Json format. Is this common and anyone faced like this before?
Note: If I change the method type from JsonResult to ActionResult, it shows nothing.

Table not updating (tableSorter with Knockout )

I writing code for updating table on every 5 sec.
I have used table sorter with knocknot....
the data is been loading perfect on first iteration after that the data is append to previous data..instead of updating..
Here is my code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="scripts/jquery-1.7.1.min.js"></script>
<script src="scripts/knockout-3.4.0.js"></script>
<script src="scripts/knockout.mapping-latest.js"></script>
<link href="scripts/tableSorter/theme.blue.css" rel="stylesheet" />
<script src="scripts/tableSorter/jquery.tablesorter.js"></script>
<script src="https://cdn.jsdelivr.net/tablesorter/2.17.4/js/widgets/widget-scroller.js"></script>
<script src="scripts/tableSorter/jquery.tablesorter.widgets.js"></script>
<title>Dynamic Data from sqlData</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="text" data-bind="value: vm.AccountArray().length" />
<table border="1">
<thead>
<tr>
<th>accountNumber
</th>
<th>accountName
</th>
<th>account balance
</th>
</tr>
</thead>
<tbody data-bind="foreach: { data: AccountArray, as: 'Account' }">
<tr>
<td data-bind="text: Account.AccountNumber"></td>
<td data-bind="text: Account.AccountName"></td>
<td data-bind="text: Account.AccountBalance"></td>
</tr>
</tbody>
</table>
</div>
</form>
<script>
function Account(accountNumber, accountName, accountBalance) {
this.AccountNumber = ko.observable(accountNumber);
this.AccountName = ko.observable(accountName);
this.AccountBalance = ko.observable(accountBalance);
}
var viewModel;
var table;
var hg;
var vm = new function () {
this.amount = ko.observableArray();
this.AccountArray = ko.observableArray();
}
$(function () {
table = $("table").tablesorter({
theme: 'blue',
widthFixed: true,
widgets: ['zebra', 'stickyHeaders', 'filter', 'scroller', 'resizable'],
widgetOptions: {
reorder_axis: 'x', // 'x' or 'xy'
reorder_delay: 100,
reorder_helperClass: 'tablesorter-reorder-helper',
reorder_helperBar: 'tablesorter-reorder-helper-bar',
reorder_noReorder: 'reorder-false',
reorder_blocked: 'reorder-block-left reorder-block-end',
reorder_complete: completed,// callback
scroller_height: 300,
scroller_barWidth: 17
}
});
$('.tablesorter-scroller-table').css({
height: '',
'max-height': '300px'
});
function completed() {
}
function AutoReload() {
$.ajax({
type: "POST",
url: "Dynamic_Data_Creation.aspx/GetDataAjax",
contentType: "application/json; charset=utf-8",
data: {},
dataType: "json",
success: function (response) {
hg = $('.tablesorter-scroller-table').prop("scrollTop");
vm.AccountArray.removeAll();
vm.AccountArray().length = 0;
vm.AccountArray.valueHasMutated();
ko.mapping.fromJSON(response.d, null, vm.AccountArray); // updata response data
$("table").trigger("update");
$('.tablesorter-scroller-table').prop("scrollTop", hg); // updating the scroll position to table
$('.tablesorter-scroller-table').css("scrollTop", $('.tablesorter-scroller-table').prop("scrollTop"));
setTimeout(function () { AutoReload(); }, 5000); //reload on every 5 seconds.
},
failure: function (response) {
alert(response.d);
}
});
}
AutoReload();
});
ko.applyBindings(vm);
</script>
</body>
</html>
I don't think you're getting any benefit from Knockout. You're having to manipulate the DOM to synchronize it with your data. That's what Knockout is supposed to do.
A relatively simple custom binding handler will take care of this for you.
ko.bindingHandlers.sortable = {
init: function(el, va) {
var arg = ko.unwrap(va());
$(el).tablesorter(arg.options);
arg.data.subscribe(function() {
$(el).trigger('update');
});
}
};
The binding looks like
<table data-bind="sortable: {data: accountArray, options: tableOptions}" border="1">
Here's a fiddle that demonstrates adding elements, clearing the array, and setting the whole array at once.

AJax for Remove from Cart is not doing anything

I am trying to have this AJAX code working. When I run the WebStore it display a list of categories which If I clicked on 1 category, I can then select a product. The product show up and I can added to the cart. After it's been added to the cart, I clicked on Remove from the Cart and nothing is refreshing. I based my solution on the MVC Music Store and I also read the old solution was not updated for this Ajax Part. I found this instead and I guess I am missing something.
I noticed an URL change localhost:49523/Panier#. Any idea why a # is there ?
Thanks
index.cshtml from panier
#model Tp1WebStore3.ViewModels.ShoppingCartViewModel
#{
ViewBag.Title = "Shopping Cart";
}
<script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<script src="/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function handleUpdate(context) {
// Load and deserialize the returned JSON data
var json = context.get_data();
var data = Sys.Serialization.JavaScriptSerializer.deserialize(json);
// Update the page elements
$('#row-' + data.DeleteId).fadeOut('slow');
$('#cart-status').text('Cart (' + data.CartCount + ')');
$('#update-message').text(data.Message);
$('#cart-total').text(data.CartTotal);
}
</script>
<h3>
<em>Details</em> du panier:
</h3>
<p class="button">
#Html.ActionLink("Checkout >>", "AddressAndPayment", "Checkout")
</p>
<div id="update-message">
</div>
<table>
<tr>
<th>
Produit
</th>
<th>
Prix (unitaire)
</th>
<th>
Quantite
</th>
<th></th>
</tr>
#foreach (var item in Model.CartItems)
{
<tr id="row-#item.ProduitId">
<td>
#Html.ActionLink(item.Produit.Description,"Details", "Panier", new { id =
item.ProduitId }, null)
</td>
<td>
#item.Produit.Prix
</td>
<td id="item-count-#item.ProduitId">
#item.Quantite
</td>
<td>
Remove from Cart
</td>
</tr>
}
<tr>
<td>
Total
</td>
<td></td>
<td></td>
<td id="cart-total">
#Model.CartTotal
</td>
</tr>
</table>
PanierController.cs
// AJAX: /ShoppingCart/RemoveFromCart/5
[HttpPost]
public ActionResult RemoveFromCart(int id)
{
// Remove the item from the cart
var cart = ShoppingCart.GetCart(this.HttpContext);
// Get the name of the album to display confirmation
string produitDescription = dbProduit.Paniers
.Single(item => item.PanierId == id).Produit.Description;
// Remove from cart
int itemCount = cart.RemoveFromCart(id);
// Display the confirmation message
var results = new ShoppingCartRemoveViewModel
{
Message = Server.HtmlEncode(produitDescription) +
" has been removed from your shopping cart.",
CartTotal = cart.GetTotal(),
CartCount = cart.GetCount(),
ItemCount = itemCount,
DeleteId = id
};
return Json(results);
Modify Index.cshtml
#model Tp1WebStore3.ViewModels.ShoppingCartViewModel
#{
ViewBag.Title = "Shopping Cart";
}
<script src="/Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('.RemoveLink').click(function () {
$.ajax({
url: '/Panier/RemoveFromCart',
data: { id: $(this).data('id') },
cache: false,
success: function (result) {
$('#row-' + result.DeleteId).fadeOut('slow');
$('#cart-status').text('Cart (' + result.CartCount + ')');
$('#update-message').text(result.Message);
$('#cart-total').text(result.CartTotal);
}
});
return false;
});
});
</script>
I am adding also the
ShoppingCart.cs
public int RemoveFromCart(int id)
{
// Get the cart
var cartItem = db.Paniers.Single(
cart => cart.CartId == ShoppingCartId
&& cart.ProduitId == id);
int itemCount = 0;
if (cartItem != null)
{
if (cartItem.Quantite > 1)
{
cartItem.Quantite--;
itemCount = cartItem.Quantite;
}
else
{
db.Paniers.Remove(cartItem);
}
// Save changes
db.SaveChanges();
}
return itemCount;
I got more information. When I ran Chrome with PF12 and Network, I saw a page not found
In my Panier I got this key (newly created) for the CartId : dbfac4de-ae5e-4fbf-a44a-f6bb8ee3f2fc
In Chrome it complaining about this:
RemoveFromCart?id=dbfac4de-ae5e-4fbf-a44a-f6bb8ee3f2fc&_=1394045298037
/Panier
I don't understand the next part of the key (concatenation) &_=1394045298037
My ProduitId are define like this for the key: 3
Can anyone explain this to me ?
You have a remove anchor:
Remove from Cart
and some javascript handleUpdate function which is absolutely never called:
<script type="text/javascript">
function handleUpdate(context) {
// Load and deserialize the returned JSON data
var json = context.get_data();
var data = Sys.Serialization.JavaScriptSerializer.deserialize(json);
// Update the page elements
$('#row-' + data.DeleteId).fadeOut('slow');
$('#cart-status').text('Cart (' + data.CartCount + ')');
$('#update-message').text(data.Message);
$('#cart-total').text(data.CartTotal);
}
</script>
You also seem to be using an extremely outdated version of jquery:
<script src="/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
and a dinosaurly old, stone age outdated and deprecated Microsoft AJAX scripts:
<script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
So start by removing the dinosaurly old scripts from your ASP.NET MVC application as well as the handleUpdate function which is absolutely never used.
Then you could write some jQuery ajax function that will subscribe to the click event of your anchor and perform an AJAX request:
<script type="text/javascript">
$(function() {
$('.RemoveLink').click(function() {
$.ajax({
url: '/ShoppingCart/RemoveFromCart',
data: { id: $(this).data('id') },
cache: false,
success: function(result) {
$('#row-' + result.DeleteId).fadeOut('slow');
$('#cart-status').text('Cart (' + result.CartCount + ')');
$('#update-message').text(result.Message);
$('#cart-total').text(result.CartTotal);
}
});
return false;
});
});
</script>
Also you should learn how to debug your AJAX calls in your web browser. All modern web browsers (such as Google Chrome) come with javascript debugging tools that would help you debug and analyze such problems. So don't hesitate to fire your debugging toolbar using F12 and look at the Network tab. It will provide you useful information about all network requests (including AJAX) that the browser is making. The Console tab will show you any potential javascript errors you might be having in your code. So instead of saying on StackOverflow that nothing happens when you click on some anchor, next time use your javascript debugging toolbar to analyze what happens under the covers.

Categories