I am really hoping someone can help me. I am trying to build a real time Gauge that is connected to a SQL Server Express with signalR.
Here's my code
Startup class
using System;
using System.Configuration;
using System.Threading.Tasks;
using Microsoft.Owin;`enter code here`
using Owin;
using Microsoft.AspNet.SignalR;
[assembly: OwinStartupAttribute(typeof(Real_Time_Gauge.Startup))]
namespace Real_Time_Gauge
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
Hub class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using Microsoft.AspNet.SignalR.Hubs;
namespace Real_Time_Gauge
{
public class GaugeHub : Hub
{
Int16 value = 0;
[HubMethodName("sendNotifications")]
public string SendNotifications()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["GaugeConnection"].ConnectionString))
{
string query = "SELECT top 1 [value] FROM [Values]";
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Notification = null;
DataTable dt = new DataTable();
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new `enter code here`
OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
dt.Load(reader);
if (dt.Rows.Count > 0)
{
value = Int16.Parse(dt.Rows[0]["value"].ToString());
}
}
}
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<GaugeHub>();
return context.Clients.All.RecieveNotification(value);
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
GaugeHub nHub = new GaugeHub();
nHub.SendNotifications();
}
}
}
}
web.config
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="GaugeConnection" connectionString="Server=72NHD02-PC\SQLEXPRESS;Database=SignalR;User Id=**;Password=*******;" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
</configuration>
Html and javascript
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Gauge Test</title>
<link href="css/style.css" rel="stylesheet" />
<script src="Scripts/jquery-1.6.4.min.js"></script>
<script src="Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="/signalr/hubs"></script>
<script src="Scripts/gauge.min.js"></script>
<script src="Scripts/script.js"></script>
<script src="signalr/hubs"></script>
</head>
<body>
<input type="text" id="value" />
<canvas id="gauge"></canvas>
<script type="text/javascript">
var gauge = new Gauge({
renderTo: 'gauge',
width: document.body.offsetWidth,
height: document.body.offsetHeight,
glow: true,
units: 'KPI',
title: "Sales",
minValue: 0,
maxValue: 100,
majorTicks: ['0', '10', '20', '30', '40', '50', '60', '70', '80', '90', '100'],
minorTicks: 10,
strokeTicks: false,
highlights: [
{ from: 0, to: 40, color: 'rgb(237, 28, 36)' },
{ from: 40, to: 60, color: 'rgb(242, 101, 34)' },
{ from: 60, to: 70, color: 'rgb(247, 147, 29)' },
{ from: 70, to: 80, color: 'rgb(255, 242, 0)' },
{ from: 80, to: 100, color: 'rgb(0, 144, 58)' }
],
colors: {
plate: '#222',
majorTicks: '#f5f5f5',
minorTicks: '#ddd',
title: '#fff',
units: '#ccc',
numbers: '#eee',
needle: { start: 'rgba(240, 128, 128, 1)', end: 'rgba(255, 160, 122, .9)' }
}
});
gauge.onready = function () {
setInterval(function () {
gauge.setValue($value);
}, 1000);
};
gauge.draw();
window.onresize = function () {
gauge.updateConfig({
width: document.body.offsetWidth,
height: document.body.offsetHeight
});
};
</script>
</body>
</html>
Gauge javascript
/// <reference path="jquery-1.6.4.min.js" />
/// <reference path="jquery.signalR-2.2.0.min.js" />
$(function() {
// Declare a proxy to reference the hub.
var notifications = $.connection.notificationHub;
// Create a function that the hub can call to broadcast messages.
notifications.client.recieveNotification = function () {
// Add the message to the page.
$('#value').text(value);
};
// Start the connection.
$.connection.hub.start().done(function () {
notifications.server.sendNotifications();
}).fail(function (e) {
alert(e);
});
//$.connection.hub.start();
});
$value = value;
My database is called SignalR with Values as table id=1 value=80.
I would greatly appreciate any help as i am new to signalR.
Thanks
Related
I am having difficulties to get google charts to work in ASP.NET Core MVC. When using the example from google it works fine (Source: https://developers.google.com/chart/interactive/docs/gallery/columnchart):
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses', 'Profit'],
['2014', 1000, 400, 200],
['2015', 1170, 460, 250],
['2016', 660, 1120, 300],
['2017', 1030, 540, 350]
]);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
</script>
</head>
<body>
<div id="columnchart_material" style="width: 800px; height: 500px;"></div>
</body>
</html>
My problem is that my data has different lengths in columns, thus sticking to the example above I have sometimes ['Year', 'Sales'] or ['Year', 'Sales', 'Expenses'] and I am trying to make this plot dynamic.
I am using Viewbag to pass around my data, thus I have made available my model with:
#{
dataModel.ChartPlotData = ViewBag.ChartPlotData as ChartPlotData
}
I have defined a class holding my data:
public class ChartPlotData
{
public List<List<object>> Data;
public ChartPlotData() { Data = new List<List<object>>(); }
}
The data is filled via:
private ChartPlotData MockData()
{
var retVal = new ChartPlotData();
var line = new List<object>();
line.Add("Time");
line.Add("Test");
retVal.Data.Add(line);
line = new List<object>();
line.Add("0:05");
line.Add(0);
retVal.Data.Add(line);
line = new List<object>();
line.Add("0:10");
line.Add(1);
retVal.Data.Add(line);
return retVal;
}
Now I was trying to change the part in the plot data as:
var data = google.visualization.arrayToDataTable( #dataModel.ChartPlotData.Data )
It did not work. Next, I extended my class as:
public object[][] DataArray
{
get
{
var tmpLst = new List<object[]>();
foreach (var lstObj in Data)
{
tmpLst.Add(lstObj.ToArray());
}
return tmpLst.ToArray();
}
}
Still no luck. I tried various other things by instantiating the data as
var data = new google.visualization.DataTable();
then tried adding columns and setting cells like
// Add columns
data.addColumn('string', 'Employee Name');
data.addColumn('date', 'Start Date');
// Add empty rows
data.addRows(6);
data.setCell(0, 0, 'Mike');
data.setCell(0, 1, {v:new Date(2008,1,28), f:'February 28, 2008'});
data.setCell(1, 0, 'Bob');
data.setCell(1, 1, new Date(2007, 5, 1));
data.setCell(2, 0, 'Alice');
data.setCell(2, 1, new Date(2006, 7, 16));
data.setCell(3, 0, 'Frank');
but somehow I can not get it to work. Any help would be highly appreciated.
Edit:
I tried this:
var data = google.visualization.arrayToDataTable([
#for (var i = 0; i < 1; i++)
{
<text> ['Time','Test'],['00:00',0],['00:05',1] </text>
}
]);
It works. But when I replace it with a string containing the list, it stops working:
var data = google.visualization.arrayToDataTable([
#for (var i = 0; i < 1; i++)
{
<text> #dataModel.dataAsString </text>
}
]);
I can now narrow it down to the following problem. This works fine:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', { 'packages': ['bar'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(
#for (var i = 0; i < 1; i++)
{
<text> [['Time', 'Test'], ['0:00', 0], ['0:05', 1]] </text>
}
);
var options = {
chart: {
title: 'Title',
subtitle: 'Some subtitle'
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
</script>
</head>
<body>
<div id="columnchart_material" style="width: 800px; height: 500px;"></div>
</body>
</html>
If I define a variable within my datamodel that includes exactly this string and replace
var data = google.visualization.arrayToDataTable(
#for (var i = 0; i < 1; i++)
{
<text> #dataModel.MyDataAsString </text>
}
);
it stops working.
I solved the problem. First, I created a field in html like
<p id="demo"></p>
Then in the java script one can use this to get the representation of the data:
var tmpData = google.visualization.arrayToDataTable([['Time', 'Test',], ['0:00', 1], ['0:05', 0.5]]);
document.getElementById("demo").innerHTML = tmpData.toJSON();
I then created a data class in C# that can generate this structure:
{"cols":[{"label":"Time","type":"string"},{"label":"Test","type":"number"}],"rows":[{"c":[{"v":"0:00"},{"v":1}]},{"c":[{"v":"0:05"},{"v":0.5}]}]}
Setting the value of the field using a variable
<p id="field">#StringRepresentation</p>
and then:
tmpJason = document.getElementById("field").innerHTML;
var data = new google.visualization.DataTable(tmpJason);
I have a task that, need to sync my websites's full calendar with google calendar private data. I could able to extract data from google, but while trying to display that to the Jquery full calendar, it shows an error that TypeError: $(...).fullCalendar is not a function, but when page loads full calender is loading properly. I'm getting this error only when refreshing the calendar after fetching data from google.
Here is the code i'm using:
<!DOCTYPE html>
<html>
<head>
<title>Google Calendar API Quickstart</title>
<meta charset='utf-8' />
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.css' />
</head>
<body>
<button id="authorize-button" style="display: none;">Authorize</button>
<button id="signout-button" style="display: none;">Sign Out</button>
<pre id="content"></pre>
<div id='calendar'></div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.js'></script>
<script type="text/javascript">
var events = [];
$('#calendar').fullCalendar({
eventSources: [
// your event source
{
events: events,
color: 'black', // an option!
textColor: 'yellow' // an option!
}
// any other event sources...
]
});
var CLIENT_ID = 'My Id';
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"];
var SCOPES = "https://www.googleapis.com/auth/calendar.readonly";
var authorizeButton = document.getElementById('authorize-button');
var signoutButton = document.getElementById('signout-button');
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
function initClient() {
gapi.client.init({
discoveryDocs: DISCOVERY_DOCS,
clientId: CLIENT_ID,
scope: SCOPES
}).then(function () {
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
});
}
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
listUpcomingEvents();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
function refreshCalander(eventData) {
$('#calendar').fullCalendar({
eventSources: [
// your event source
{
events: eventData,
color: 'black', // an option!
textColor: 'yellow' // an option!
}
// any other event sources..
]
});
}
function listUpcomingEvents() {
gapi.client.calendar.events.list({
'calendarId': 'primary',
'timeMin': (new Date()).toISOString(),
'showDeleted': false,
'singleEvents': true,
'maxResults': 10,
'orderBy': 'startTime'
}).then(function (response) {
var googleEvents = response.result.items;
if (googleEvents.length > 0) {
for (i = 0; i < googleEvents.length; i++) {
var event = googleEvents[i];
var when = event.start.dateTime;
if (!when) {
when = event.start.date;
}
events.push({ "title": event.summary, "start": when });
}
refreshCalander(events);
}
});
}
</script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
</body>
</html>
I was pointed to this GITHub sample code by David Fowler himself to track SignalR users and states. I have implemented all of it and it works great except I can't figure out the displaying of Hub connection state changes. I have this which doesn't seem to work. Does anyone know why?
!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style>
#state {
width: 20px;
height: 50px;
}
</style>
</head>
<body>
<h3 id="msg"></h3>
<div id="state"></div>
<script src="../Scripts/jquery-1.10.2.min.js"></script>
<script src="../Scripts/jquery.signalR-2.0.2.min.js"></script>
<script src="signalr/hubs"></script>
<script>
$(function () {
var userTracking = $.connection.alphaHub;
// Need at least one callback for events to be raised on the hub
userTracking.client.void = function () { };
$.connection.logging = true;
$.connection.hub.stateChanged(function (change) {
if (change.newState === $.signalR.connectionState.connected) {
$('#state').css('background-color', 'green');
} else if (change.newState === $.signalR.connectionState.reconnecting) {
$('#state').css('background-color', 'yellow');
} else if (change.newState === $.signalR.connectionState.disconnected) {
$('#state').css('background-color', 'red');
}
});
$.connection.hub.disconnected(function () {
setTimeout(function () {
$.connection.hub.start();
}, 1000);
});
});
</script>
</body>
</html>
My Hub is shown partially here:
public class AlphaHub : Hub
{
public override async Task OnConnected()
{
try
{
var name = Context.User.Identity.Name;
using (savitasEntities2 entities = new savitasEntities2())
{
var user = entities.SUsers
.Include(u => u.SConnections)
.SingleOrDefault(u => u.UserName == name);
if (user == null)
{
user = new SUser
{
UserName = name,
SConnections = new List<SConnection>()
};
entities.SUsers.Add(user);
}
user.SConnections.Add(new SConnection
{
ConnectionID = Context.ConnectionId,
UserAgent = Context.Request.Headers["User-Agent"],
LastActivity = DateTimeOffset.UtcNow
});
// entities.SaveChanges();
await entities.SaveChangesAsync();
}
}
public override async Task OnDisconnected()
{
try
{
using (savitasEntities2 db = new savitasEntities2())
{
var connection = await db.SConnections.FindAsync(Context.ConnectionId);
db.SConnections.Remove(connection);
await db.SaveChangesAsync();
}
}
catch (Exception ex)
{
c.LogError(ex.Message, "AlphaHub.cs" + " - " + this.GetType().FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name);
}
}
Looks like your hubs can't be found.
Change:
<script src="signalr/hubs"></script>
to:
<script src="~/signalr/hubs"></script>
Error: 0x800a138f - Microsoft JScript runtime error: Unable to get value of the property 'unobtrusive': object is null or undefined
Index.cshtml listed here at the bottom is where my problems occur.
BundleConfig.cs:
using System.Web;
using System.Web.Optimization;
namespace MyWebMVC
{
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
"~/Scripts/jquery-ui-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*",
"~/Scripts/jquery.unobtrusive*"
));
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/site.css"));
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
"~/Content/themes/base/jquery.ui.core.css",
"~/Content/themes/base/jquery.ui.resizable.css",
"~/Content/themes/base/jquery.ui.selectable.css",
"~/Content/themes/base/jquery.ui.accordion.css",
"~/Content/themes/base/jquery.ui.autocomplete.css",
"~/Content/themes/base/jquery.ui.button.css",
"~/Content/themes/base/jquery.ui.dialog.css",
"~/Content/themes/base/jquery.ui.slider.css",
"~/Content/themes/base/jquery.ui.tabs.css",
"~/Content/themes/base/jquery.ui.datepicker.css",
"~/Content/themes/base/jquery.ui.progressbar.css",
"~/Content/themes/base/jquery.ui.theme.css"));
}
}
}
_rootLayout.cshtml:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
<link href="#System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Content/css")" rel="stylesheet" type="text/css" />
<script src="#System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Scripts/js")" type="text/javascript"></script>
#Html.DevExpress().GetStyleSheets(
new StyleSheet { ExtensionSuite = ExtensionSuite.NavigationAndLayout },
new StyleSheet { ExtensionSuite = ExtensionSuite.Editors },
new StyleSheet { ExtensionSuite = ExtensionSuite.HtmlEditor },
new StyleSheet { ExtensionSuite = ExtensionSuite.GridView },
new StyleSheet { ExtensionSuite = ExtensionSuite.PivotGrid },
new StyleSheet { ExtensionSuite = ExtensionSuite.Chart },
new StyleSheet { ExtensionSuite = ExtensionSuite.Report },
new StyleSheet { ExtensionSuite = ExtensionSuite.Scheduler }
)
#Html.DevExpress().GetScripts(
new Script { ExtensionSuite = ExtensionSuite.NavigationAndLayout },
new Script { ExtensionSuite = ExtensionSuite.HtmlEditor },
new Script { ExtensionSuite = ExtensionSuite.GridView },
new Script { ExtensionSuite = ExtensionSuite.PivotGrid },
new Script { ExtensionSuite = ExtensionSuite.Editors },
new Script { ExtensionSuite = ExtensionSuite.Chart },
new Script { ExtensionSuite = ExtensionSuite.Report },
new Script { ExtensionSuite = ExtensionSuite.Scheduler }
)
</head>
<body>
#Html.DevExpress().Splitter(settings => {
settings.Name = "MainSplitter";
settings.AllowResize = false;
settings.Orientation = System.Web.UI.WebControls.Orientation.Vertical;
settings.FullscreenMode = true;
settings.SeparatorVisible = false;
settings.Styles.Pane.Border.BorderWidth = System.Web.UI.WebControls.Unit.Pixel(0);
settings.Styles.Pane.Paddings.Padding = System.Web.UI.WebControls.Unit.Pixel(0);
settings.Panes.Add(pane => {
pane.Name = "Header";
//pane.ScrollBars = System.Web.UI.WebControls.ScrollBars.Auto;
pane.Size = System.Web.UI.WebControls.Unit.Pixel(140);
pane.MinSize = System.Web.UI.WebControls.Unit.Pixel(83);
pane.PaneStyle.BorderBottom.BorderWidth = System.Web.UI.WebControls.Unit.Pixel(1);
pane.PaneStyle.CssClass = "headerPane";
pane.SetContent(() => {
Html.RenderPartial("HeaderPartialView");
});
});
settings.Panes.Add(pane => {
pane.Name = "Content";
pane.PaneStyle.CssClass = "mainContentPane";
pane.MinSize = System.Web.UI.WebControls.Unit.Pixel(375);
pane.PaneStyle.BackColor = System.Drawing.Color.White;
pane.PaneStyle.BorderBottom.BorderWidth = System.Web.UI.WebControls.Unit.Pixel(1);
pane.SetContent(RenderBody().ToHtmlString());
pane.ScrollBars = System.Web.UI.WebControls.ScrollBars.Auto;
});
settings.Panes.Add(pane => {
pane.Name = "Footer";
pane.Size = System.Web.UI.WebControls.Unit.Pixel(25);
pane.PaneStyle.CssClass = "footerPane";
pane.SetContent(() => {
Html.RenderPartial("FooterPartialView");
});
});
Scripts.Render("~/bundles/jqueryval");
Scripts.Render("~/bundles/jquery");
}).GetHtml()
</body>
</html>
_mainLayout.cshtml:
#{ Layout = "~/Views/Shared/_rootLayout.cshtml"; }
#Html.DevExpress().Splitter(settings => {
settings.Name = "ContentSplitter";
settings.Width = System.Web.UI.WebControls.Unit.Percentage(100);
settings.Height = System.Web.UI.WebControls.Unit.Percentage(100);
settings.Styles.Pane.Paddings.Padding = System.Web.UI.WebControls.Unit.Pixel(0);
settings.Styles.Pane.Border.BorderWidth = System.Web.UI.WebControls.Unit.Pixel(0);
settings.Panes.Add(subpane => {
subpane.Name = "ContentCenter";
subpane.PaneStyle.CssClass = "contentPane";
subpane.Separator.Visible = DevExpress.Utils.DefaultBoolean.True;
subpane.ScrollBars = System.Web.UI.WebControls.ScrollBars.Auto;
subpane.Separator.SeparatorStyle.Border.BorderWidth = System.Web.UI.WebControls.Unit.Pixel(1);
subpane.Separator.SeparatorStyle.BorderTop.BorderWidth = System.Web.UI.WebControls.Unit.Pixel(0);
subpane.SetContent(RenderBody().ToHtmlString());
});
}).GetHtml()
Index.cshtml: (this is where my script is getting the error)
<link rel="stylesheet" type="text/css" href="#Url.Content("~/Content/Docking/CSS/Widgets.css")" />
<script type="text/javascript">
function displaySuccess(result) {
popup.Show();
}
function PrepareValidationScripts(form) {
if (!form)
return;
if (form.attr("data-executed"))
return;
$.validator.unobtrusive.parse(form); // <----- this is where I get the error
form.attr("data-executed", "true");
}
</script>
#{
//this is where I render my partial views
<snip.....>
<snip.....>
<snip.....>
}
In your Layout you should first include jQuery and then jQueryval:
Scripts.Render("~/bundles/jquery");
Scripts.Render("~/bundles/jqueryval");
The reason for this is because the jQuery.validate plugin depends on jQuery and the order of inclusion of your scripts is important.
Also I would recommend you putting all your custom scripts in a specifically dedicated section that is placed after the other main scripts:
Scripts.Render("~/bundles/jquery");
Scripts.Render("~/bundles/jqueryval");
RenderSection("Scripts", required: false)
and then inside your view put all your scripts in this section so that the order is preserved:
#section Scripts {
<script type="text/javascript">
function displaySuccess(result) {
popup.Show();
}
function PrepareValidationScripts(form) {
if (!form)
return;
if (form.attr("data-executed"))
return;
$.validator.unobtrusive.parse(form);
form.attr("data-executed", "true");
}
</script>
}
#{
//this is where I render my partial views
<snip.....>
<snip.....>
<snip.....>
}
Of course the same stands true for your CSS styles. You should place them in a specifically dedicated section in the <head> of the document.
I am trying to implement KendoUI Grid control in my ASP.NET MVC application.
I know KendoUI guys have given numerous examples but its not working for me.
My Model code is :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data;
namespace KendoGrid.Models
{
public class status
{
public string SiteId { get; set; }
public string SiteName { get; set; }
public string SiteStatus { get; set; }
public static List<status> StatusInfo()
{
SqlConnection sconn = new SqlConnection(#"Data Source=DS-7071BC8FDEE6\SQLEXPRESS;Initial Catalog=AmanoTest;User ID=sa;Password=india#123");
SqlCommand cmd = new SqlCommand("select * from SiteMaster", sconn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
status cstat;
List<status> statlist = new List<status>();
foreach (DataRow dr1 in dt.Rows)
{
cstat = new status();
cstat.SiteId = dr1[0].ToString();
cstat.SiteName = dr1[1].ToString();
cstat.SiteStatus = dr1[2].ToString();
statlist.Add(cstat);
}
return statlist;
}
}
}
My Controller Code is :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KendoGrid.Models;
using Kendo.Mvc.UI;
namespace KendoGrid.Controllers
{
public class statusController : Controller
{
//
// GET: /status/
public ActionResult Index()
{
return View();
}
public ActionResult Site()
{
//List<status> status = status.GetStatus();
List<status> temp = status.StatusInfo();
ViewData["table"] = temp;
return View();
}
}
}
And my view (.cshtml page) is:
#model KendoGrid.Models.status
#using Kendo.Mvc.UI
#*#{
Layout = null;
}
*#
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Site</title>
</head>
<body>
<div>
#(Html.Kendo().Grid(Model)()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(p => p.siteID);
columns.Bound(p => p.siteID);
columns.Bound(p => p.siteID);
})
.Pageable()
.Sortable()
.Scrollable()
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(false)
)
)
</div>
</body>
</html>
On executing it says :
The best overloaded method match for
'Kendo.Mvc.UI.Fluent.WidgetFactory.Grid(System.Data.DataTable)' has
some invalid arguments
Look like you are missing couple step here. Please go through this step n this might resolve your problem
http://docs.kendoui.com/getting-started/using-kendo-with/aspnet-mvc/helpers/grid/ajax-binding
You can use
var url = "/DesktopModules/MyServices/API/ATSManageClient/GetAllProjectsTechnologyBased?PortalId=210&tabid=95&Technology=" + selectedplatform;
var element = $("#grid").kendoGrid({
//debugger;
type: "odata",
dataSource: {
transport: {
read: url
},
schema: {
model: {
fields: {
RecievedDate: { type: "date" }
}
}
},
pageSize: 100
},
columnMenu: true,
scrollable: true,
filterable: true,
resizable: true,
sortable: true,
detailTemplate: kendo.template($("#template").html()),
detailInit: detailInit,
dataBound: function () {
},
columns: [
{
field: "ProjectID",
title: "Action",
template: "<a href='/Dashboard/Communication?ProjectID=#=ProjectID#'>View Communication</a>",
width: "20%"
},
//s debugger;
{
field: "ClientName",
width: "20%",
title: "Client",
template: "<a href='Accounts/UpdateClient.aspx?ClientId=#=ClientID#'> #= ClientName #</a>",
attributes: {
title: "#=ClientName#"
}
},
{
field: "ProjectTitle",
width: "20%",
title: "Project",
template: "<a href='Project/EditProject.aspx?ProjectID=#=ProjectID#'> #= ProjectTitle #</a>",
attributes: {
title: "#=ProjectTitle#"
}
},
{
field: "ColorList",
width: "20%",
template: kendo.template($("#template2").html()),
title: "Status"
},
{
field: "RecievedDate",
width: "20%",
title: "Check List Status",
template: ""
},
{
field: "RecievedDate",
width: "20%",
title: "Opened Bugs",
template: ""
}
],
pageable: {
// we don't set any DataSource here
pageSizes: [100, 150, 200]
}
});