I'm using the Kendo UI scheduler with the timeline view and I need to populate the left column with data from my database. I'm struggling to understand how to do it.
The part I'm talking about is where in the demo appears:
resources: [{
field: "roomId",
name: "Rooms",
dataSource: [{
text: "Meeting Room 101",
value: 1,
color: "#6eb3fa"
}, {
text: "Meeting Room 201",
value: 2,
color: "#f58a8a"
}],
title: "Room"
}]
So instead of saying "meeting Room 101", I want it to load data from the server and the number of cells will vary, so the column will be dynamic.
Is this possible? Could someone point me to a good explanation on how to do it?
I don't know if the solution is still of interest to you, but intended for Google;)
You can use the Kendo DataSource:
var rooms = new kendo.data.DataSource({
transport: {
read: {
url: "/get/rooms",
dataType: "json"
}
}
and then just assign the datasource
resources: [
{
field: "roomId",
name: "Room",
dataSource: rooms,
title: "Room"
}
Model (Example):
public class RoomResourcesModel
{
public string text { get; set; }
public int value { get; set; }
public string color { get; set; }
}
Controller (Example):
public ActionResult Rooms()
{
var model = new List<RoomResourcesModel>();
model.Add(new RoomResourcesModel { text = "Room 1", value = "1", color = "#CD6600" });
model.Add(new RoomResourcesModel { text = "Room 2", value = "2", color = "#FF3030" });
model.Add(new RoomResourcesModel { text = "Room 3", value = "3", color = "#FFD700" });
return Json(model, JsonRequestBehavior.AllowGet);
}
How can statistical data be shown in a chart format using the Razor Chart Helper of MVC ?
When you want to display your data in graphical form, you can use Chart helper. The Chart helper can render an image that displays data in a variety of chart types.
You can create a view having razor code for chart as follows(lets say its MyChart.cshtml).
Bar chart from Array with theam
#{
var myChart = new Chart(width: 600, height: 400, theme: ChartTheme.Green)
.AddTitle("Chart Title")
.AddSeries(
name: "ChartTitle",
xValue: new[] { "Col1", "Col2", "Col3", "Col4", "Col5" },
yValues: new[] { "2", "6", "4", "5", "3" })
.Write();
}
Pie chart from Array
#{
var myChart = new Chart(width: 600, height: 400, theme: ChartTheme.Green)
.AddTitle("Chart Title")
.AddSeries(
name: "ChartTitle",
chartType: "Pie",
xValue: new[] { "Col1", "Col2", "Col3", "Col4", "Col5" },
yValues: new[] { "2", "6", "4", "5", "3" })
.Write();
}
Pie chart from Array with theam
#{
var myChart = new Chart(width: 600, height: 400)
.AddTitle("Chart Title")
.AddSeries(
name: "ChartTitle",
chartType: "Pie",
xValue: new[] { "Col1", "Col2", "Col3", "Col4", "Col5" },
yValues: new[] { "2", "6", "4", "5", "3" })
.Write();
}
Bar Chart Using DB Query
#{
var db = Database.Open("DBName");
var data = db.Query("SELECT Col1, Col2 FROM Table");
var myChart = new Chart(width: 600, height: 400)
.AddTitle("Chart Title")
.DataBindTable(dataSource: data, xField: "Col1")
.Write();
}
You can use these chart views/PartialView where ever required as a src of image.
ex.
<html>
<body>
<img src="MyChart.cshtml" />
<!-- or <img src='#Url.Action("Controler","ActionNameOfChartRenderingView")' />-->
<body>
<html>
Chart Theams
Vanilla Displays red columns on a white background.
Blue Displays blue columns on a blue gradient background.
Green Displays blue columns on a green gradient background.
Yellow Displays orange columns on a yellow gradient background.
Vanilla3D Displays 3-D red columns on a white background.
SeriesChartType enumeration supports the following:
Area
Bar
BoxPlot
Bubble
Candlestick
Column
Doughnut
ErrorBar
FastLine
FastPoint
Funnel
Kagi
Line
Pie
Point
PointAndFigure
Polar
Pyramid
Radar
Range
RangeBar
RangeColumn
Renko
Spline
SplineArea
SplineRange
StackedArea
StackedArea100
StackedBar
StackedBar100
StackedColumn
StackedColumn100
StepLine
Stock
ThreeLineBreak
This is the list of names that you can pass, as strings, to the Chart helper in a Razor page.
This is Helper
namespace System.Web.Helpers
{
public class Chart
{
public Chart(int width, int height, string template = null, string templatePath = null);
public string FileName { get; }
public int Height { get; }
public int Width { get; }
public Chart AddLegend(string title = null, string name = null);
public Chart AddSeries(string name = null, string chartType = "Column", string chartArea = null, string axisLabel = null, string legend = null, int markerStep = 1, IEnumerable xValue = null, string xField = null, IEnumerable yValues = null, string yFields = null);
public Chart AddTitle(string text = null, string name = null);
public Chart DataBindCrossTable(IEnumerable dataSource, string groupByField, string xField, string yFields, string otherFields = null, string pointSortOrder = "Ascending");
public Chart DataBindTable(IEnumerable dataSource, string xField = null);
public byte[] GetBytes(string format = "jpeg");
public static Chart GetFromCache(string key);
public Chart Save(string path, string format = "jpeg");
public string SaveToCache(string key = null, int minutesToCache = 20, bool slidingExpiration = true);
public Chart SaveXml(string path);
public Chart SetXAxis(string title = "", double min = 0, double max = 0.0 / 0.0);
public Chart SetYAxis(string title = "", double min = 0, double max = 0.0 / 0.0);
public WebImage ToWebImage(string format = "jpeg");
public Chart Write(string format = "jpeg");
public static Chart WriteFromCache(string key, string format = "jpeg");
}
}
example ...
Controler
namespace MVC3ChartTest.Controllers
{
public class ChartsController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult BasicChart()
{
return View();
}
public ActionResult BasicChartWithMasterPage()
{
return View();
}
}
}
non-strongly-typed view
#model dynamic
#{
View.Title = "BasicChart";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Basic Chart</h2>
<p>
#{
var key = new Chart(width: 600, height: 400)
.AddTitle("Staff Mobility")
.AddSeries(
name: "Employee",
xValue: new[] { "Jan", "Feb", "Mar", "Api", "May", "Jun", "Jul", "Aug", "Sep"},
yValues: new[] { "2", "6", "4", "5", "3","4","9","2","5"}
)
.Write();
}
</p>
BasicChartWithMasterPage
#model dynamic
#{
View.Title = "BasicChartWithMasterPage";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>BasicChartWithMasterPage</h2>
<p><img src="BasicChart" /> </p>
Example 2
Model
//other omitted...
using System.Collections;
using System.Web.Helpers;
namespace MVC3ChartTest.Models
{
internal class PieChartData
{
public string Title { get; set; }
public Category_Sales_for_1997[] Data { get; set; }
}
public class NorthModel
{
NorthwindEntities db = new NorthwindEntities();
List<Category_Sales_for_1997> pieData;
public Chart PieChart
{
get
{
return BuildServerPieChart();
}
}
public NorthModel()
{
pieData = db.Category_Sales_for_1997.ToList<Category_Sales_for_1997>();
}
//other omitted...
Functions to return chart
private Chart BuildServerPieChart()
{
var data = new PieChartData
{
Title = "Total: " + (from y in pieData select y.CategorySales).Sum().ToString(),
Data = (from x in pieData orderby x.CategoryName descending select x).ToArray(),
};
return BindChartData(data);
}
private Chart BindChartData(PieChartData data)
{
Chart chart = new Chart(
width: 400,
height: 300,
template: ChartTheme.Green);
chart.AddTitle(data.Title);
chart.AddLegend(title: "Lengend Title", name: null);
ArrayList x_ValueArray = new ArrayList();
ArrayList y_ValuesArray = new ArrayList();
for (int i = 0; i < data.Data.Length; i++)
{
x_ValueArray.Add(data.Data[i].CategoryName);
y_ValuesArray.Add(data.Data[i].CategorySales);
}
chart.AddSeries(
name: "Employee",
chartType: "Pie",
axisLabel: "Name",
xValue: x_ValueArray,
yValues: y_ValuesArray);
return chart;
}
Controller Action
public ActionResult Index()
{
NorthModel model = new NorthModel();
return View(model);
}
View
#model MVC3ChartTest.Models.NorthModel
#{
View.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<div>
#{Model.PieChart.Write();}
</div>
In a ASP.NET MVC (Razor) project, I'm using a ListBox with Multi Select option in a Edit View,
CONTROLLER
public ActionResult Edit(int id)
{
Post post = db.Posts.Find(id);
string selectedValues = post.Tags; //This contains Selected values list (Eg: "AA,BB")
ViewBag.Tagslist = GetTags(selectedValues.Split(','));
return View(post);
}
private MultiSelectList GetTags(string[] selectedValues)
{
var tagsQuery = from d in db.Tags
orderby d.Name
select d;
return new MultiSelectList(tagsQuery, "Name", "Name", selectedValues);
}
HTML
<div class="editor-field">
#Html.ListBox("Tags", ViewBag.Tagslist as MultiSelectList)
</div>
This loads the items (Tag List) in to ListBox, but does not highlight the items in the Selected Values list.
How to fix this issue?
Thanks in advance.
I suspect that your Post class (to which your view is strongly typed) has a property called Tags. You also use Tags as first argument of the ListBox helper. This means that the helper will look into this property first and ignore the selected values you passed to the MultiSelectList. So the correct way to set a selected value is the following:
public ActionResult Edit(int id)
{
Post post = db.Posts.Find(id);
ViewBag.Tagslist = GetTags();
return View(post);
}
private MultiSelectList GetTags()
{
var tagsQuery = from d in db.Tags
orderby d.Name
select d;
return new MultiSelectList(tagsQuery, "Name", "Name");
}
and in the view:
<div class="editor-field">
#Html.ListBoxFor(x => x.Tags, ViewBag.Tagslist as MultiSelectList)
</div>
And here's a full example that should illustrate:
public class HomeController : Controller
{
public ActionResult Index()
{
var post = new Post
{
Tags = new[] { "AA", "BB" }
};
var allTags = new[]
{
new { Name = "AA" }, new { Name = "BB" }, new { Name = "CC" },
};
ViewBag.Tagslist = new MultiSelectList(allTags, "Name", "Name");
return View(post);
}
}
Also I would recommend you using view models instead of passing your domain entities to the view. So in your PostViewModel you will have a property called AllTags of type MultiSelectList. This way you will be able to get rid of the weak typed ViewBag.
I want to create a graphical chart in mvc 3 razor using the code below (thanks to DotNetJalps):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Helpers;
namespace CodeSimplifiedTest.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
return View();
}
public ActionResult DrawChart()
{
var chart = new Chart(width: 300, height: 200)
.AddSeries(
chartType: "bar",
xValue: new[] { "10 Records", "20 Records", "30 Records", "40 Records" },
yValues: new[] { "50", "60", "78", "80" })
.GetBytes("png");
return File(chart, "image/bytes");
}
}
}
But
I want to retrieve the xValues and Yvalues from a SQL Server 2008 R2 database...what code must I put after xValue: and yValue: or some code anywhere in the controller and view to retrieve data from the database? I tried Entity Framework context...but it didn't work.
Thanks
Here is what i am using to make the chart from the dbContext from EF....
public ActionResult PayorPieChart()
{
string xx = activePhysicianID;
ArrayList xValue = new ArrayList();
ArrayList yValue = new ArrayList();
XXXXXXX_MainEntities dbContext = new XXXXXXX_MainEntities();
var results = dbContext.Payor.Where(rs => rs.PhysicianIdentity.Equals(xx));
results.ToList().ForEach(rs => xValue.Add(rs.Identifier));
results.ToList().ForEach(rs => yValue.Add(rs.Strength));
var chart = new Chart(600, 300, ChartTheme.Blue);
chart.AddSeries(chartType: "Pie", xValue: xValue, yValues: yValue);
chart.AddTitle("Payor");
chart.Write("png");
return null;
}
The below link explains how to use "DataBindTable" method which binds the data from Model. Here, the data is framed inside the Model. You can get the data from sql server in the model inside the method "GetChartData".
http://weblogs.asp.net/gunnarpeipman/archive/2010/10/10/asp-net-mvc-3-beta-built-in-support-for-charts.aspx
Hope this helps!!
I wish to store an action link in the model.
Something like
public MvcHtmlString ActionLink_New
{
get { return Html.ActionLink("new", "Edit", "News", new { Area = "Admin" }, null); }
}
It appears the model needs a webviewpage context.
Failing that, I thought I would store just the route values.
public RouteValueDictionary[] RouteValue_New
{
get { return new RouteValueDictionary[] { Area = "Admin" }; }
}
//View
#Html.ActionLink("new", "Edit", "News", Model.RouteValue_New, null)
The Area in the property is red. Is either or both scenario achievable. What do i need to add to get this to work, thanks.
try this
public object RouteValue_New
{
get {
return new { Area = "Admin" };
}
}