Datatable is not loading using Asp.net MVC - asp.net-mvc

i am creating a simple crud system for my studies. I am a beginner of Asp.net MVC.i am tring to load the data from the database but i could do the task.what i tried so far i attached below. i am created database which name is skill and have a table course tried to load it dataTable.while run the progam i got the error of
Error
Uncaught TypeError: $(...).DataTable is not a function
at HTMLDocument.<anonymous> (Index:81)
at e (jquery-3.4.1.min.js:2)
at t (jquery-3.4.1.min.js:2)
Controller page
public ActionResult Index()
{
return View();
}
public ActionResult GetSkill()
{
using (skillEntities sk = new skillEntities())
{
var course = sk.courses.OrderBy(a => a.id).ToList();
return Json(new { data = course }, JsonRequestBehavior.AllowGet);
}
}
View Page
#{
ViewBag.Title = "Home Page";
}
<html>
<head>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet">
</head>
<body>
<div style="width:90%; margin:0 auto" class="tablecontainer">
<a class="popup btn btn-primary" href="/home/save/0" style="margin-bottom:20px; margin-top:20px;">Add New Employee</a>
<table id="myDatatable">
<thead>
<tr>
<th>ID</th>
<th>Course Name</th>
<th>Fee</th>
</tr>
</thead>
</table>
</div>
<script src="~/Scripts/jquery-3.4.1.js"></script>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
var oTable = $('#myDatatable').DataTable({
"ajax": {
"url": '/home/GetSkill',
"type" : "get",
"datatype": "json"
},
"columns": [
{ "data": "id", "autoWidth": true },
{ "data" : "coursename", "autoWidth" : true},
{ "data": "fee", "autoWidth": true }
]
})
})
</script>
</body>
</html>

you have included jquery library twice, try removing below line, use min.js only
<script src="~/Scripts/jquery-3.4.1.js"></script>

Related

Asp.net Mvc Ajax Record Couldn't find

i am creating the Asp.net MVC Project in Bank Balance Checking.if i enter the correct account no relevant balance want to display but not not displayed while i am running the programming i got the error was Additional information: The underlying provider failed on Open.
what i tried so far i attached below.
Index.cshtml
#{
ViewBag.Title = "Index";
}
<div class="row">
<div class="col-sm-8">
#using (Html.BeginForm("Index", "home", FormMethod.Post, new { id = "popupForm" }))
{
<table class="table table-bordered">
<caption> Add Products </caption>
<tr>
<th>Account No</th>
<th>Account Holder Name</th>
<th>Balance</th>
</tr>
<tr align="center">
<td>
<input type="text" class="form-control" placeholder="Account No" id="accno" name="accno" size="50px">
</td>
<td>
<input type="text" class="form-control" id="accname" size="25px" name="accname"
placeholder="price" disabled>
</td>
<td>
<input type="number" class="form-control" id="balance" name="balance"
placeholder="qty" size="25px" required>
</td>
</tr>
</table>
}
</div>
</div>
<hr />
#Scripts.Render("~/bundles/jquery")
#section scripts{
<script src="~/Scripts/jquery-3.4.1.js"></script>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.2/jquery-confirm.min.js"></script>
<script>
getProductcode();
function getProductcode()
{
$("#accno").empty();
$("#accno").keyup(function (e) {
var q = $("#accno").val();
if ($('#accno').val().length === 0) {
$.alert({
title: 'Error!',
content: "Please Enter the Barcode",
type: 'red',
autoClose: 'ok|2000'
});
return false;
}
$.ajax({
type: "POST",
url: '/home/Getid?id=' + $("#accno").val(),
dataType: "JSON",
success: function (data)
{
console.log(data);
$('#accname').val(data.accname);
$('#balance').val(data.balance);
},
error: function (xhr, status, error)
{
// alert("The barcode entered is not correct");
}
});
return true;
});
}
</script>
}
#section styles{
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.2/jquery-confirm.min.css">
<link rel="stylesheet" href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
}
HomeController
//you don't need this here except you want to use Dependency injection
bankEntities dc = new bankEntities();
public ActionResult Index()
{
return View();
}
public string accno { get; set; }
[HttpPost]
public JsonResult Getid(String Id)
{
var std = dc.accounts.Where(a => a.accno == Id).FirstOrDefault();
return Json(std, JsonRequestBehavior.AllowGet);
}
}

angular ui bootstrap popover not working

i am starting to learn to use angular's ui bootstrap library and trying to get a popover working. Am i missing something in my setup?
i've provided a plunker example. my requirement is to have a popover over cells in a table that gets refreshed by $interval every second.
http://plnkr.co/edit/hF3EDIRfKA1VOfSennZq?p=preview
<!DOCTYPE html>
<html ng-app="test">
<head>
<meta charset="UTF-8">
<title>angular-test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" type="text/css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular-animate.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.14.2/ui-bootstrap-tpls.min.js"></script>
<script type="text/javascript">
var app = angular.module("test", ['ngAnimate', 'ui.bootstrap']);
app.controller("testCtrl", function($scope, $interval) {
var stats = [{
"name": "john",
"stat1": 3,
"stat2": 5
}];
var count = 0;
$scope.getTestInfo = function() {
$scope.count = count++;
$scope.stats = stats;
}
$interval(function(){$scope.getTestInfo();}, 1000);
});
</script>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-lg-4" ng-controller="testCtrl" ng-init="count=0">
<table id="table1" class="table table-hover table-condensed">
<thead>
<tr>
<th>column1</th>
<th>column2</th>
<th>column3</th>
</tr>
</thead>
<tbody class="bg-info">
<tr ng-repeat="stat in stats">
<td uib-popover="testcolumn1">{{stat.name}}</td>
<td uib-popover="{{stat.stat1}}">{{stat.stat1 + count}}</td>
<td uib-popover="testcolumn3">{{stat.stat2}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
You just need to add the metadata (popover-trigger etc.) for the popover modal. I forked your plunkr to demonstrate. http://plnkr.co/edit/d1eAf2NEAA9mCXmNN5LC?p=preview

Grails / Groovy Attribute value quote wasn't closed : Google Visualization API - data from Domain Class

I am using GGTS: 3.6.4,
Grails: 2.4.4
jdk 1.7.51
google-visualization:1.0
I am trying to pass data from a domain class to my view to display a map using the Google Visualization plug-in. I believe I am passing this data to my GSP incorrectly. I can make the data render on screen, in text, in the acceptable format, please see my GSP for def mapData.
When I use
def mapData =[<g:each in="${places}" var="place" status="i">[${place.lat}, ${place.lon}, "${place.name }"],</g:each>]
I get this error:
Message:Attribute value quote wasn't closed (elementId="map" columns= "${mapColumns}" data= "[
Any tips on how I can change my GSP to get the data from my domain class?
Domain Class:
package zmapapp
class ThingLoc {
String name
Float lat
Float lon
static constraints = {
lat()
lon()
name()
}
}
Controller:
package zmapapp
class ThingLocController {
def scaffold = true
def map (){
def places = ThingLoc.list()
[places: places]
}
}
GSP:
<html>
<head>
<title>Google Visualization API plugin</title>
<meta name="layout" content="main" />
<gvisualization:apiImport/>
</head>
<body>
<%
def mapColumns = [['number', 'Lat'], ['number', 'Lon'], ['string', 'Name']]
def mapData = [[37.4232, -122.0853, 'Work'], [37.4289, -122.1697, 'University'], [37.6153, -122.3900, 'Airport'], [37.4422, -122.1731, 'Shopping']]
%>
<script type="text/javascript">
function selectHandler(e) {
alert('A table row was selected');
}
function readyHandler(e) {
console.log('Table is ready');
}
</script>
<h2>See Map Below </h2>
<gvisualization:map elementId="map"
columns= "${mapColumns}"
data= "${mapData}" />
<table cellpadding="2" cellspacing="0">
<td>
Map
</td>
<td>
<div id="map" style="width: 400px; height: 300px"></div>
</td>
</tr>
</table>
[<g:each in="${places}" var="place" status="i">[${place.lat}, ${place.lon}, "${place.name }"],</g:each>]
</body>
I ended up not using the def mapColumns or mapData and instead used the google syntax found here: https://developers.google.com/chart/interactive/docs/gallery/map
here's my update gsp:
<html>
<head>
<title>Dat Map tho</title>
<meta name="layout" content="main" />
<gvisualization:apiImport/>
<script type="text/javascript">
google.load('visualization', '1', { 'packages': ['map'] });
google.setOnLoadCallback(drawMap);
function drawMap() {
var data = google.visualization.arrayToDataTable([
['Lat', 'Long', 'Name'],
<g:each in="${places}" var="place" status="i">[${place.lat}, ${place.lon}, "${place.name }"],</g:each>
]);
var options = { showTip: true };
var map = new google.visualization.Map(document.getElementById('chart_div'));
map.draw(data, options);
};
</script>
</head>
<body>
<div id="chart_div"></div>
<br><br>
Map Visualization Information
</body>
</html>

MVC4 HTML.ValidationMessageFor is not showing validation messages

I am trying to figure out ,why my validation messages are not showing up?
Here is my Razor page
#model MyViewModel
#{
Layout = "~/Views/Shared/_MainLayout.cshtml";
var listErrors = ViewBag.listErrors as Array;
}
<section class="selectconfiguration">
<h3 class="active">Add Rule</h3>
<div class="con-section">
#{Html.EnableClientValidation(true);}
#{Html.EnableUnobtrusiveJavaScript();}
#using (Html.BeginForm("AddRules", "Aliases", "HttpPost"))
{
#Html.ValidationSummary(true)
<table>
<tr>
<td class="phone-options-label-column">
<div class="editor-label">
#Html.Label("Alias String:")
</div>
</td>
<td>
#Html.EditorFor(m => m.AliasString,new {#id="txtAliasString"})
</td>
<td> #Html.ValidationMessageFor(m => m.AliasString)</td>
</tr>
<tr>
<td class="options-label-column">
<div class="editor-label">
#Html.Label("Select an Associated Model:")
</div>
</td>
<td>
#Html.DropDownList("ddlModels", new SelectList(Model.Models, "Id", "Name", ""), "Unknown", new { #class = "mselectDDContItem" })
</td>
<td>
</td>
</tr>
</table>
}
<div>
<input type="submit" value="Add Rule" id="btnAddRule" name="AddRule" />
</div>
</div>
</section>
Here is my ViewModel
public class MyViewModel
{
[Required(ErrorMessage = "alias string required")]
[StringLength(30, ErrorMessage = "AliasString cannot be larger than 30 characters")]
public string AliasString { get; set; }
public IEnumerable<IParameter> Models { get; set; }
public string StatusMessage { get; set; }
}
On clciking the addRules button triggers my jquery clcik event
<script type="text/javascript">
$(document).ready(function () {
$("#btnAddRule").click(function (e) {
e.preventDefault();
var params = {
'aliasString': $("#txtAliasString").val(),
'modelId': $("#ddlModels").val()
};
$.ajax({
url: "/Aliases/AddRules",
type: "POST",
dataType: 'json',
data: JSON.stringify(params),
async: false,
cache: false,
traditional: true,
contentType: 'application/json',
}).done(function () {
}).complete(function () {
}).success(function (dv) {
});
});
});
</script>
and I have these script references also on my layout page
<script src="#Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.11.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.treeview.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.ui.selectmenu.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/global.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.nad.session.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcValidation.js")"></script>
I dont understhnad why the validations are not firing.
If I click the button with the empty textbox also ,I can see post back happens and modelstate.isValid is returning true to the controller.
In my jquery button click function ,I added ,$('#myForm').valid() and then my validation started showing up.
$("#btnAddRule").click(function (e) {
if ($('#myForm').valid()) {
}
});
Just put submit button inside the form and validation would work

Can't get simplest ASP.NET MVC3 form to post asynchronously using AJAX

I can't see why the following form performs a full postback instead of asynchronously using AJAX. Request.IsAjaxRequest() is always false. I think I've followed all the examples correctly. What am I doing wrong?
Here's the view:
#(Layout = null)
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.4.4.js" type="text/javascript"></script>
</head>
<body>
<div>
<div id="update"></div>
#using(Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "update" }))
{
<input type="submit" value="test" />
}
</div>
</body>
</html>
And here's the controller:
using System.Web.Mvc;
namespace TheHoges.Web.Controllers
{
public class TestController : Controller
{
public ActionResult Index()
{
if (Request.IsAjaxRequest())
{
// never gets here
return Content("it worked");
}
return View();
}
}
}
For reference:
AJAX and MVC 3
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
Do you see this in you web.config?
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
If, yes, including the library above should solve your problem.
Just to be thorough I created a test page. Works peachy...
#{
ViewBag.Title = "Home Page";
}
#(Layout = null)
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
</head>
<body>
<div>
<div id="update">
</div>
#using(Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "update" }))
{
<input type="submit" value="test" />
}
</div>
</body>
</html>

Resources