Charts not showing on ASP.NET MVC page - c#

I am pretty new to asp.net so I tried to add a simple bar chart with charts.js to my view but all I get is an empty page.
Controller
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
List<string> iData = new List<string>();
List<string> iData2 = new List<string>();
iData.Add("Sam");
iData2.Add("555");
iData.Add("Alex");
iData2.Add("666");
iData.Add("Michael");
iData2.Add("777");
ViewBag.Value_List = iData2;
ViewBag.Name_List = iData;
return View();
}
}
View:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Charts</title>
<script src="~/Scripts/Chart.min.js"></script>
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
var barChartData =
{
labels: [#Html.Raw(ViewBag.Name_List)],
datasets: [{
label: 'ChartTest',
backgroundColor: [
"#f990a7",
"#aad2ed",
"#9966FF",
"#99e5e5",
"#f7bd83",
],
borderWidth: 2,
data: [#ViewBag.Value_List]
}]
};
window.onload = function () {
var ctx1 = document.getElementById("barcanvas").getContext("2d");
window.myBar = new Chart(ctx1,
{
type: 'bar',
data: barChartData,
options:
{
title:
{
display: true,
text: "ChartTest"
},
responsive: true,
maintainAspectRatio: true
}
});
}
</script>
</head>
<body>
<div style="text-align: center">
<canvas id="barcanvas"></canvas>
</div>
</body>
</html>
I tried to help me with some tutorials but nothing worked for me.
Can someone tell me what I am doing wrong?

Two changes needed:
Serialize the data into JSON in the controller:
using System.Web.Script.Serialization;
var js = new JavaScriptSerializer();
ViewBag.Value_List = js.Serialize( iData2);
ViewBag.Name_List = js.Serialize(iData);
Remove the extra square brackets in the view:
labels: #Html.Raw(ViewBag.Name_List),
data: #Html.Raw(ViewBag.Value_List)
You need to create "drop in" JavaScript to represent the data.
labels: ["555","666","777"] ,
data: ["Sam","Alex","Michael"]

Related

Autocomplete script in asp mvc

Hi I am new to webpage development, verified all related questions in Stack over flow but still I cant get the solution.
I am trying to include Autocomplete function in a input box and its works fine if my Layout = null; in View file, where as if I used my existing view template ViewBag.Title = "Home Page"; Autocomplete function is not working
View File:
#model IEnumerable<AspNetRoleBasedSecurity.Models.PostModel>
#{
ViewBag.Title = "Home Page";
}
<div class="row search-row">
<input class="search ui-autocomplete-input" type="text" id="CityName" placeholder="What do you need help with?"/>
<a class="buttonsearch btn btn-info btn-lg" href="search-results.html">Search</a>
</div>
Script Used:
<script type="text/javascript">
$(document).ready(function () {
$("#CityName").autocomplete({
source: function (request,response) {
$.ajax({
url: "/Home/GetRecord",
type: "POST",
dataType: "json",
data: { prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Title, value: item.Title };
}))
}
})
},
});
});
</script>
Ref
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" />
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
C#
public JsonResult GetRecord(string prefix)
{
DataSet ds = PostRepo.GetName(prefix);
List<search> searchlist = new List<search>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
searchlist.Add(new search
{
Title= dr["Title"].ToString(),
Tags = dr["Tags"].ToString(),
Id = dr["Id"].ToString()
});
}
return Json(searchlist, JsonRequestBehavior.AllowGet);
}
I cant understand why its not working if ViewBag.Title = "Home Page"; No error message received but autocomplete feature not works.
Please help me in understanding the concept.
May be Check Layout out page scripts that you have referred
and don't add in child views any scripts because scripts may conflict with multiple versions
here is the working example auto complete

Bind a list with jquery datatable

I have made an MVC application which would display a set of file names located in a given directory. To display the list, i have used normal table in my view.Since the view returns a huge list of file names, i am asked to use jquery datatable,which i dont have much idea about. I tried by going through lot of suggestions but could not return the list at all. Please have a look at the code below.
Controller:
public class SupportingChannelController : Controller
{
// GET: SupportingChannel
List<SupportingChannel> _list = null;
SupportingChannelBL _bl = new SupportingChannelBL();
SupportingChannelDataVM _data = new SupportingChannelDataVM();
public ActionResult GetSupportingChannelData()
{
_list = _bl.channel();
_data._model = _list;
return View("SupportingChannel", _data);
}
View
#model MultiRequestInterface.Models.SupportingChannelDataVM
#{
ViewBag.Title = "SupportingChannel";
}
<h2>Supporting Channels</h2>
#using (Html.BeginForm("getComType","SupportingChannel",FormMethod.Post))
{
<div>
<style>
table,th,td
{
border: 1px solid black;
border-collapse: collapse;
align-content:center;
}
</style>
<div style="border:solid;width:100%;overflow-x:auto;">
<table id="table" align="center" style="width:100%" class="display">
<thead>
<tr>
<th>Communication Type</th>
<th>Communication Description</th>
</tr>
</thead>
</table>
</div>
<input type="submit" name="submit" value="submit" />
</div>
if (TempData["testmsg"] != null)
{
<script type="text/javascript">
alert("#TempData["testmsg"]");
</script>
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script
src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js">
</script>
<script type="text/javascript">
$(document).ready(function ()
{
var table = $('#table').DataTable();
var data = table.data;
$.ajax({
url: 'GetSupportingChannelData/SupportingChannel',
dataType: 'json',
contentType: "application/json;",
data: JSON.stringify(data),
success: function () {
},
});
});
</script>
Since i am returning a list to the view, i just want some help as in howcan i pass this list as data to the jquery datatable..
Thanks in advance
Since you've already created HTML table containing column headers, just use built-in AJAX call function in DataTable to fetch data as JSON:
$('#table').DataTable({
"ajax": {
"url": "#Url.Action("GetSupportingChannelData", "SupportingChannel")", // action method URL
"type": "GET",
"datatype": "json"
},
, columns: [
{ data: 'columnName1' },
{ data: 'columnName2' },
{ data: 'columnName3' },
{ data: 'columnName4' },
{ data: 'columnName5' }
],
// other settings
});
Then use return type JsonResult to return your list of model as JSON data that will passed to DataTable (I assumed there is another action method which returns view where DataTable should belongs to):
public class SupportingChannelController : Controller
{
List<SupportingChannel> _list = null;
SupportingChannelBL _bl = new SupportingChannelBL();
// other class-level fields
// returns view to render DataTable
public ActionResult GetChannelData()
{
return View();
}
// returns JSON data from list of model values
public ActionResult GetSupportingChannelData()
{
// other stuff
_list = _bl.channel();
// other stuff
return Json(new { data = _list }, JsonRequestBehavior.AllowGet);
}
}
Additional references:
Implement jQuery Datatable in ASP.NET MVC application
AJAX CRUD Operation With jQuery DataTables In ASP.NET MVC 5

Kendo grid not displaying data MVVM

I am not sure what I am doing wrong
My HTML
<head>
<title></title>
<script src="include/libraries/jquery/jquery-2.2.2.min.js"></script>
<script src="include/libraries/jquery/jquery-2.2.2.intellisense.js"></script>
<script src="include/libraries/jquery/jquery-2.2.2.js"></script>
<link href="include/libraries/kendo/css/kendo.bootstrap.min.css" rel="stylesheet" />
<link href="include/libraries/kendo/css/kendo.common-bootstrap.min.css" rel="stylesheet" />
<script src="include/libraries/kendo/js/kendo.all.js"></script>
<script src="include/libraries/kendo/js/kendo.all.min.js"></script>
<script src="include/libraries/kendo/js/kendo.aspnetmvc.min.js"></script>
<script src="include/libraries/kendo/js/kendo.custom.min.js"></script>
<script src="include/libraries/kendo/js/kendo.timezones.min.js"></script>
<meta charset="utf-8" />
</head>
<body>
<div id="grid">
<div class="demo-section k-content wide">
<div>
<h4>Add or update a record</h4>
<div data-role="grid"
data-editable="true"
data-toolbar="['create', 'save']"
data-columns="[
{ 'field': 'CourseID' },
{ 'field': 'CourseName' },
{ 'field': 'IsActive' },
]"
data-bind="source: courses,
visible: isVisible,
events: {
save: onSave
}"
style="height: 200px"></div>
</div>
</div>
<script>
var viewModel = kendo.observable( {
isVisible: true,
onSave: function(e) {
kendoConsole.log("event :: save(" + kendo.stringify(e.values, null, 4) + ")");
},
courses: new kendo.data.DataSource({
schema: {
model: {
id: "CourseID",
fields: {
CourseID: { type: "number" },
CourseName: { type: "string" },
IsActive:{type:"boolean"}
}
}
},
batch: true,
transport: {
read: {
type:"GET",
url: "http://localhost:51447/api/Courses",
dataType: "jsonp"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
}
})
});
kendo.bind($("#grid"), viewModel);
</script>
</div>
</body>
My Controller Code
// GET: api/Courses
public IQueryable<object> GetCourses()
{
return db.Courses.Select(
o => new
{
CourseID = o.CourseID,
CourseName = o.CourseName,
IsActive = o.IsActive
});
//}).Where(l => l.IsActive == false);
}
My JSON
[{"CourseID":1,"CourseName":"Beauty Therapy","IsActive":true},{"CourseID":2,"CourseName":"Software Development","IsActive":true},{"CourseID":3,"CourseName":"Bookkeeping and Accounting","IsActive":true}]
I finally got this fixed. The structure of my solution is such that it has a WebAPI and a Web app. So in the WebApiConfig.cs file I added the line config.EnableCors(); and it worked.
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}

Select Items and display in same view. Return results to controller

I am new to mvc and fairly young with Javascript so I apologize for the wrong/missing code. I am trying to make a view where the user has a drop down list and items selected via btnAdd will be dynamically displayed in the same view below the btnAdd button. I am assuming the best way to do this would be with JavaScript. After the user has made there choices they will click the btnckout button and there selections will be returned to the controller. Here is what I have so far. I am a little stuck so any help would be appreciated!
View:
#model OnlineTakeout.Models.ProductView
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="~/Scripts/jquery-2.1.0.min.js"></script>
<title>Index</title>
</head>
<body>
#using (Html.BeginForm()){
<div>
Pick Product:
<br />
#Html.DropDownListFor(m=>m.ProductId, Model.Products)
<br />
<p>
<input type="button" value="AddToOrder" id="btnAdd" />
</p>
</div>
}
<div>
#using (Html.BeginForm()) {
//Added Items would display here after individual btnAdd button presses
<p>
<input type="button" value="CheckOut" id="btnChkOut" />
</p>
}
</div>
</body>
<script>
$(function () {
$("#btnAdd").click(addProduct);
})
$(function () {
$("#btnChkOut").click(saveProducts);
})
var productList = [];
var id = $("#ProductId").val();
// This function would also display these items on view
function addProduct() {
productList.push(id);
};
function saveProducts() {
$.post("/Product/Index/" + productList());
}
}
</script>
Controller:
public class ProductController : Controller
{
//
// GET: /Product/
public ActionResult Index()
{
var model = new ProductView();
var products = new List<Product> { new Product { ProductId = 1, Name = "Product One", Price = 1.00m },
{ new Product { ProductId = 2, Name = "Product Two", Price = 2.00m } }};
model.Products = new SelectList(products, "ProductId", "Name");
return View(model);
}
[HttpPost]
public JsonResult Index(int[] prodList)
{
return Json("Index");
}
The way I usually do this is by using jQuery.
You will need to create an event handler in jQuery for the change event of your drop down list that is supposed to trigger this change. When that fired, post to an action in your controller that is going to bind a partial controller and return the partial view. It is important to have a return type of ActionResult - that will return the HTML back to success method of your post. Then just embed the HTML on the page and you are done.

parameter complex object is coming into JavaScript function as undefined

On Page 1 I get the object I need:
ProjectSearchCriteria = (GBLProjectSearchCriteria)Session[GblConstants.SESSION_PROJECT_SEARCH_CRITERIA];
I'm trying to pass this to an API on a page load of Page 2.
Page 2:
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<link href="../x.css" type="text/css" rel="stylesheet">
<link href="../Content/kendo.common.min.css" rel="stylesheet" />
<link href="../Content/kendo.default.min.css" rel="stylesheet" />
</head>
<body>
<form id="frmProjectSearchResults" runat="server">
</form>
<script src="../Scripts/ProjectsTreeView.js"> </script>
<script type="text/javascript">
CreateProjectTree(<%= ProjectSearchCriteria %>);
</script>
</body>
</html>
And this is the JavaScript function:
function CreateProjectTree(searchCriteria)
{
debugger;
var projects = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: "../api/projects?searchcriteria =" + searchCriteria,
contentType: "application/json"
},
parameterMap: function (data, operation) {
return JSON.stringify(data);
}
},
schema: {
model: {
children: "seasons"
}
}
});
$("#treeview").kendoTreeView({
dataSource: projects,
loadOnDemand: true,
dataUrlField: "LinksTo",
checkboxes: {
checkChildren: true
},
dataTextField: ["Title"],
select: treeviewSelect
});
function treeviewSelect(e) {
var node = this.dataItem(e.node);
window.open(node.NotificationLink, "_self");
}
}
Can anyone help me understand what I'm doing wrong?
Maybe this:
<script type="text/javascript">
CreateProjectTree("\"" + <%= ProjectSearchCriteria %> + "\"");
</script>

Categories