Jtable and MVC, doesn't load to view - c#

I'm new to MVC and Jquery. Trying to use jtable, but nothing happens when loading page.
This is my view.
<link href="~/scripts/jtable.2.4.0/themes/metro/blue/jtable.css"
rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="~/scripts/jtable.2.4.0/jquery.jtable.js">
</script>
#using (Html.BeginForm("Upload", "Hotels", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<div id="HotelsTable"> </div>
<script type="text/javascript">
$(document).ready(function () {
//Prepare jtable plugin
$('#HotelsTable').jtable({
title: 'List of Hotels',
paging: true,
pageSize: 10,
sorting: true,
defaultSorting: 'Name ASC',
actions: {
listAction: '#Url.Action("HotelsList")'
},
fields: {
Hotel1: {
title: 'Region',
width: '10%'
},
Hotel2: {
title: 'Hotel',
list: false,
width: '10%'
},
Hotel3: {
title: 'Desde',
type: 'date',
displayFormat: 'yy-mm-dd',
width: '8%',
list: false
},
Hotel4: {
title: 'Hasta',
type: 'date',
displayFormat: 'yy-mm-dd',
width: '8%'
},
Hotel5: {
title: 'Comentarios',
width: '8%',
}
}
});
//Load person list from server
$('#HotelsTable').jtable('load');
});
</script>
}
</body>
</html>
This is my control:
[HttpPost]
public JsonResult HotelsList()
{
try
{
List<Models.Models.HotelElem> hotels =
db.Database.Fetch<Models.Models.HotelElem>("SELECT * FROM Hotels");
return Json(new { Result = "OK", Records = hotels });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
While debugging it doesn't even go my HotelList() method. Need some help, what could it be?
Thanks!

Found solution! Maybe will be useful for someone.
Forgot to add
<script src="~/scripts/jquery-1.9.1.min.js"></script>
<script src="~/scripts/jquery-ui-1.9.2.min.js"></script>
...)

Related

No data returned when I incorporate dataTable in ASP.NET MVC

I am new to datatables. I am trying to incorporate datatable into an existing ASP.NET MVC application. Below is my Index.cshtml page. I tried to incorporate datatable in this code:
<table id="BookAssignmentTable" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>Book</th>
<th>Office</th>
<th>Group</th>
<th>Updated By</th>
<th>Updated On</th>
</tr>
</thead>
</table>
<link href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap.min.css" rel="stylesheet" />
<link href="https://stackpath.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.21/js/dataTables.bootstrap.min.js"></script>
<script>
var Popup, dataTable;
$(document).ready(function () {
dataTable = $("#BookAssignmentTable").DataTable({
"ajax": {
"url": "/BookAssign/GetData",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "Book" },
{ "data": "Office" },
{ "data": "Group" },
{ "data": "UpdatedBy" },
{ "data": "UpdatedOn" },
{
"data": "ID", "render": function (data) {
return "<a class='btn btn-default btn-sm' onclick=PopupForm('#Url.Action("StoreOrEdit", "bookAssignment_new")/" + 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 Book Assignment Details',
height : 500,
width : 700,
close: function () {
Popup.dialog('destroy').remove();
}
});
});
}
</script>
Below is my BookAssignController:
public ActionResult GetData()
{
using (ACREmployeeEntities db= new ACREmployeeEntities())
{
List<bookAssignment_new> bookList = db.bookAssignment_new.ToList<bookAssignment_new>();
return Json(new { data = bookList }, JsonRequestBehavior.AllowGet);
}
}
This is in my route.config file:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "BookAssign", action = "Index", id = UrlParameter.Optional }
);
}
When I run my code, I see this URL, but I don't see any to data.
https://localhost:44374/BookAssign/Index
When I changed the url to
https://localhost:44374/BookAssign/getdata
the debugger stops at the getData method in the controller and returns the correct data. I am not sure what am I don't wrong and why I don't see any data.
Below is the screenshot:
For the first time appearance of .cshtml, you could do the following process:
First you should add <tbody></tbody> behind your <thead></thead> section.
In <tbody></tbody> section, you add a loop like this:
#for(var i = 0; i < yourData.ItsLength; i++)
{
<tr>
<td>yourData[i].YourFirstAttribute</td>
<td>yourData[i].YourSecondAttribute</td>
<td>yourData[i].YourThirdAttribute</td>
</tr>
}
P/S: I recommend you put your js script separately outside .cshtml file.

problem loading Jquery Datatable using a textbox

Hope that someone can help me with this.
this is my Controller
namespace PruebaBusquedaRun.Controllers
{
public class TestController : Controller
{
MandatosModel md = new MandatosModel();
// GET: Test
public ActionResult Index()
{
return View();
}
public ActionResult TestDataTable(string run)
{
List<MandatosModel> lmm = new List<MandatosModel>();
DataSet ds = new DataSet();
Int64 asd = Convert.ToInt64(run);
Conexion.ConexionOra conexora = new Conexion.ConexionOra();
ds = conexora.getMandatosPorRun(asd);
foreach (DataRow dr in ds.Tables[0].Rows)
{
lmm.Add(new MandatosModel
{
FOLIO = Convert.ToInt64(dr["FOLIO"]),
IDCAJA = Convert.ToInt64(dr["IDCAJA"]),
NOMBRES = dr["NOMBRES"].ToString(),
A_PATERNO = dr["A_PATERNO"].ToString(),
A_MATERNO = dr["A_MATERNO"].ToString(),
CORREO = dr["CORREO"].ToString()
});
}
return Json(new { data = lmm }, JsonRequestBehavior.AllowGet);
}
}
}
And Here is my View
<div style="width:90%; margin:0 auto;">
#using (Html.BeginForm("TestDataTable", "Test", FormMethod.Post))
{
<br />
<input type="text" id="run" name="run" required />
<button type="button" id="boton">Click Me!</button>
<input type="submit" name="asd" value="Buscar Mandatos" />
<br />
<br />
}
<table id="myTable">
<thead>
<tr>
<th>Folio</th>
<th>Nombres</th>
<th>Apellido Paterno</th>
<th>Apellido Materno</th>
<th>Correo</th>
</tr>
</thead>
</table>
</div>
<style>
tr.even {
background-color: #F5F5F5 !important;
}
</style>
#* Load datatable css *#
<!--<link href="//cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css"
rel="stylesheet" />-->
<link href="~/Content/DataTable/jquery.dataTables.css" rel="stylesheet" />
#* Load datatable js *#
#section Scripts{
<!--<script src="//cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js">
</script>-->
<script src="~/Scripts/DataTable/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$('#myTable').DataTable({
"ajax": {
"url": "/Test/TestDataTable",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "FOLIO", "autoWidth": true },
{ "data": "NOMBRES", "autoWidth": true },
{ "data": "A_PATERNO", "autoWidth": true },
{ "data": "A_MATERNO", "autoWidth": true },
{ "data": "CORREO", "autoWidth": true }
]
});
});
</script>
}
The main thing that i want to do is to pass a parameter to the TestDataTable method (run) and display the data in the DataTable, in the current state i'm able to execute my procedure and get all the data that i want, but after brings the data it does not return the view with the table, it returns only the plain data.
Sorry for the mistakes and my poor english.
Please help :(
i use a web api , i send my data like this
ajax: {
url: _json,
type: "GET"
},
so in your _json is url + parameters
/Test/TestDataTable?run=demo
--
you need i think is, ajax calling your controller
public JsonResult TestDataTable(string run)
{
try
{
//code
}
catch (Exception ex)
{
return Json(ex.Message);
}
}
some ajax like this.
$.ajax({
cache: !1,
url: '#Url.Action("TestDataTable", "TestController")',
async: !1,
data: { run: demo.val() },
success: function (e) { // data for datatables },
error: function (e, c, t) { alert(e.responseText) }
});

Searching a jqGrid from Jquery UI Dialog causes search string from request to be an empty string

My requirement needs me to display a jqGrid in an Jquery UI popup dialog.
Behaviour noticed :
I am able to perform paging, sorting, searching but when I call the same in a Jquery UI dialog it does not search. It only does paging and sorting.
My Research :
I noticed when I called the same JgGrid without it being displayed in the Jquery UI dialog it does searching, paging and sorting.
HTML Code below:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<link rel="stylesheet" type="text/css" media="screen" href="css/ui-lightness/jquery-ui-1.10.4.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" />
<script src="js/jquery-1.11.1.min.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.10.4.custom.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.src.js" type="text/javascript"></script>
<script type="text/javascript">
var curRowNum = 0;
var curPressedButton = '';
var curPressedNum = 0;
$(function () {
$("#test").click(function () {
$("#dialog-form-lookup-site").dialog('open');
})
$("#tblSiteLookup").jqGrid({
url: 'Handlers/SitesHandler.ashx?l=sa',
datatype: "json",
height: 200,
width: 600,
mtype: 'post',
loadonce : true,
colNames: ['Guid', 'Company', 'Customer Site', 'Annual Consumption (kWh)'],
],
colModel: [
{ name: 'Guid', index: 'Guid', search: true, searchoptions: { sopt: ['eq']} },
//{ name: 'price', index: 'price', width: 60, search: true, stype: 'text', searchoptions: { dataInit: datePick, attr: { title: 'Select Date'}} },
{name: 'Company', index: 'Company', width: 70, sortable: true, editable: false, searchtype: "number", search: true, stype: 'text', searchoptions: { sopt: ['eq']} },
{ name: 'CustomerSite', index: 'CustomerSite', width: 70, sortable: true, editable: false, search: true, stype: 'text', searchoptions: { sopt: ['eq']} },
{ name: 'AnnualConsumption', width: 100, sortable: true, editable: false }
],
rowNum: 10,
rowList: [10, 20, 30],
pager: '#pager11',
sortname: 'Company',
viewrecords: true,
sortorder: "desc",
caption: "Site"
});
$("#tblSiteLookup").jqGrid('navGrid', '#pager11', { search: true, edit: false, add: false, del: false, searchtext: "search" });
$("#dialog-form-lookup-site").dialog({
autoOpen: false,
height: 450,
width: 700,
modal: true,
dialogClass: 'no-close',
buttons: {
"OK": function () {
},
Cancel: function () {
$(this).dialog("close");
}
},
close: function () {
}
});
});
</script>
<title></title>
</head>
<body>
<form id="HtmlForm" runat="server">
<div>
<input id="test" type="button" value="Test Sites List" />
</div>
<div id="dialog-form-lookup-site" title="Lookup Site">
<table id="tblSiteLookup" cellpadding="0" cellspacing="0">
</table>
<div id="pager11" style="width:500px">
</div>
</div>
</form>
</body>
</html>
Code on the server side in the SitesHandler.ashx:
public class SitesHandler : IHttpHandler , IRequiresSessionState
{
/// <summary>
/// Handle the request
/// </summary>
/// <param name="context"></param>
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
string siteLists = GetSitesList();
response.Write(siteLists);
}
}
Question :
How do I call this from the above JQuery UI popup so that the search
works ?
Downgrading the jQuery library from 1.11.1 to 1.9.1 fixed the issue. Looks like the new Jquery library may not be compatible to the search feature of the JgGrid.
Code belows shows commented library code and library code in use which fixed this issue, hope this helps just in case you all bump into this issue:
<%--<script src="js/jquery-1.11.1.min.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.10.4.custom.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.src.js" type="text/javascript"></script>--%>
<script src="js/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.9.2.min.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.src.js" type="text/javascript"></script>

installing http://fullcalendar.io/

I have this:
Index.cshtml:
<script src="#Url.Content("~/Scripts/jquery-1.3.2.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.7.2.custom.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/fullcalendar.js")" type="text/javascript"></script>
<link href="#Url.Content("~/Content/fullcalendar.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/jquery-ui-1.7.2.custom.css")" rel="stylesheet" type="text/css" />
<div id="calendar"></div>
<script type="text/javascript">
$(document).ready(function () {
$('#calendar').fullCalendar({
theme: true,
header: {
left: '',
center: '',
right: ''
},
defaultView: 'agendaDay',
editable: false,
events: "/Calendar/GetEvents/"
});
});
//Set up the date picker and wire it's onSelect function
//to the FullCalendar plugin.
$("#datepicker").datepicker({
inline: true,
onSelect: function (dateText, inst) {
var d = new Date(dateText);
$('#calendar').fullCalendar('gotoDate', d);
}
});
//Set some defaults for the fullCalendar, including the URL to
//get the data from...
$('#calendar').fullCalendar(
{
theme: true,
defaultView: "basicWeek",
firstDay: 1,
events: "/Schedule/GetCalendar/"
});
</script>
<style scoped>
</style>
AgendaController:
public class AgendaController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
return View();
}
private long ToUnixTimespan(DateTime date)
{
TimeSpan tspan = date.ToUniversalTime().Subtract(
new DateTime(1970, 1, 1, 0, 0, 0));
return (long)Math.Truncate(tspan.TotalSeconds);
}
}
I am trying to install the free FullCalender Ajax plugin: http://fullcalendar.io/
But if I run the application and go to:http://localhost:41787/Agenda nothing is displayed. I put the <div id="calendar"></div> in the Index view file. But nothing happens. I don't see the Calendar.
And I put the scripts in the BundleConfig:
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/fullcalendar.css",
"~/Content/fullcalendar.print.css"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/fullcalendar.js" ));
but I dont understand why I get the 404 not found error
ok, the scripts are running now correctly, but still dont see anything if I go to:
http://localhost:41787/Calendar
Request URL:http://localhost:41787/Scripts/fullcalendar.js
Request Method:GET
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4,nb;q=0.2
Cache-Control:no-cache
Connection:keep-alive
oke, I have it now like this:
<script type="text/javascript" src="~/Scripts/fullcalendar.js"></script>
<script type="text/javascript" src="~/Scripts/jquery-1.11.0.js"></script>
<script type="text/javascript">
$(document).ready(function () {
alert("hallo");
});
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month'
},
defaultDate: 'new Date()',
editable: true,
events:
[
{
title: 'Bi-weekly Meeting',
start: '2014-07-09',
color: 'red'
},
{
title: 'Tournament',
start: '2014-07-07',
end: '2014-07-10',
color: 'darkorange'
},
{
title: 'Test Event',
url: 'http://google.com/',
start: '2014-07-28'
}
]
});
So I see the Hallo message if I load the page, but by this line: $('#calendar').fullCalendar({
it says:
Uncaught TypeError: undefined is not a function Index:141
(anonymous function)
oh, oke, I triied like this:
$(document).ready(function () {
$("#calendar").fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month'
},
defaultDate: 'new Date()',
editable: true,
events:
[
{
title: 'Bi-weekly Meeting',
start: '2014-07-09',
color: 'red'
},
{
title: 'Tournament',
start: '2014-07-07',
end: '2014-07-10',
color: 'darkorange'
},
{
title: 'Test Event',
url: 'http://google.com/',
start: '2014-07-28'
}
]
});
and now it works :)
});

i am using j query pie chat in simple asp dot net page. how to bind value form database in j query pie chat

I am useing jquery pie chart in ASP.NET. pie chart doing work properly, but I want to bind values from database. How can I do bind database values in the pie chart. I have created a table in the database and I want to fetch values from database into the pie chart.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(function ()
{
var chart;
$(document).ready(function ()
{
// Radialize the colors
Highcharts.getOptions().colors = $.map(Highcharts.getOptions().colors, function (color)
{
return {
radialGradient: {
cx: 0.5,
cy: 0.3,
r: 0.7
},
stops: [
[0, color],
[1, Highcharts.Color(color).brighten(-0.3).get('rgb')] // darken
]
};
});
// Build the chart
chart = new Highcharts.Chart(
{
chart: {
renderTo: 'container',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Browser market shares at a specific website, 2010'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function ()
{
return '<b>' + this.point.name + '</b>: ' + this.percentage + ' %';
}
}
}
},
series: [
{
type: 'pie',
name: 'Browser share',
data: [
['Firefox', 45.0],
['IE', 26.8],
{
name: 'Chrome',
y: 12.8,
sliced: true,
selected: true
}, ['Safari', 8.5],
['Opera', 6.2],
['Others', 0.7]
]
}
]
});
});
});
</script>
</head>
<body>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<di v id="container" style="min-width: 400px; height: 400px; margin: 0 auto">
</div>
</body>
Simple solution would be to place your values from the DB in a hidden field and then access them using javascript and get their values to be used as part of the series.
This is the ASPX:
....
<asp:HiddenField ID="FireFoxDataValueFromDB" runat="server" />
<asp:HiddenField ID="IEDataValueFromDB" runat="server" />
....
This is the CS:
Page_Load Event()
{
if (!IsPostBack)
{
FireFoxDataValueFromDB = getFFDBValue();
IEDataValueFromDB = getIEDBValue
}
}
....
This is the Javascript:
var FFVal = $("#FireFoxDataValueFromDB").val();
var IEVal = $("#IEDataValueFromDB").val();
and then use it as the series data:
series: [
{
type: 'pie',
name: 'Browser share',
data: [
['Firefox', FFVal],
['IE', IEVal],
{
name: 'Chrome',
y: 12.8,
sliced: true,
selected: true
}, ['Safari', 8.5],
['Opera', 6.2],
['Others', 0.7]
]
}...

Categories

Resources