example of highchart for mvc4 - asp.net-mvc

friends I'm new to highchart ,need your help to create chart in MVC 4 ,I write the code on Home controller like...
public class HomeController : Controller
{
public ActionResult Index()
{
Highcharts chart = new Highcharts("chart")
.SetCredits(new Credits { Enabled = false })
.InitChart(new Chart { DefaultSeriesType = ChartTypes.Column })
.SetTitle(new Title { Text = "Membership Overview" })
.SetXAxis(new XAxis { Categories = new[] { "Paid Members", "Active Members", "Retained Members", "New Members", "Lapsed Members" } })
.SetYAxis(new YAxis
{
Min = 0,
Title = new YAxisTitle { Text = "Total Members" }
})
.SetTooltip(new Tooltip { Formatter = "function() { return ''+ this.series.name +': '+ this.y +''; }" })
.SetPlotOptions(new PlotOptions { Bar = new PlotOptionsBar { Stacking = Stackings.Normal } })
.SetSeries(new[]
{
new Series { Name = "Total", Data = new Data(new object[] { 441, 441, 22, 30, 610 }) }
});
return View(chart);
}
}
now I don't understand how to render it on index.cshtml page.

Your Index.cshtml page should look something like this to display your chart.
#model DotNet.Highcharts.Highcharts
#{
var chart = Model;
}
if(Model != null) {
#(chart)
}

Related

Ajax Not Working on Edit Method

I have an ajax method for a cascading drop down list, similar to country - state drop down list. It works fine on Create method, but I can't get it to work on Edit method. I get this error on Edit:
POST http://localhost/Submissions/Edit/SomeAJAXMethod 500 (Internal Server Error)
There is an extra /Edit in the path that makes it not work. It works just fine on Create. I tried to add ~/. I get these errors on Create and Edit method:
POST http://localhost/Submissions/Edit/~/SomeAJAXMethod 404 (Not Found)
I tried to add ../. I get this error on Create, works fine on Edit:
POST http://localhost/SomeAJAXMethod 404 (Not Found)
How do I make it work on both Create and Edit?
Below is my controller.
//
// GET: /Submissions/Create
public ActionResult Create()
{
ViewBag.ActivityRejectCodeId = GetRejectCodesByActivity(0);
ViewBag.Activities = GetActivities();
ViewBag.Workstations = GetWorkstationsByActivity(0);
ViewBag.Platforms = GetPlatformsByWorkstation(0, 0);
ViewBag.Parts = GetPartsByPlatform(0, 0, 0);
ViewBag.StatusId = new SelectList(db.Status, "Id", "Name");
ViewBag.Technicians = GetTechnicians(0);
ViewBag.Shifts = GetShiftsByTechnician(0, 0);
ViewBag.WorkOrderId = new SelectList(db.WorkOrders, "Id", "WO");
return View();
}
//
// POST: /Submissions/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(WorkOrderSubmission workordersubmission)
{
var activityId = Int32.Parse(Request.Form["ActivityId"]);
var workstationId = Int32.Parse(Request.Form["WorkstationId"]);
var platformId = Int32.Parse(Request.Form["PlatformId"]);
var partId = Int32.Parse(Request.Form["PartId"]);
var techId = Int32.Parse(Request.Form["TechnicianId"]);
var shiftId = Int32.Parse(Request.Form["ShiftId"]);
if (ModelState.IsValid)
{
// Get the PlatformStageId from the combination of (ActivityId, WorkstationId, PlatformId, PartId)
var rs = (from ps in db.PlatformStages
join wa in db.WorkstationActivities on ps.WorkstationActivityId equals wa.Id
join pp in db.PlatformParts on ps.PlatformPartId equals pp.Id
where ps.WorkstationActivity.ActivityId == activityId
&& ps.WorkstationActivity.WorkstationId == workstationId
&& ps.PlatformPart.PlatformId == platformId
&& ps.PlatformPart.PartId == partId
select new {
ps.Id
}).FirstOrDefault();
workordersubmission.PlatformStageId = rs.Id;
// Get TechnicianShiftId from the combination of (TechnicianId, ShiftId)
rs = (from ts in db.TechnicianShifts
where ts.TechnicianId == techId
&& ts.ShiftId == shiftId
select new
{
ts.Id
}).FirstOrDefault();
workordersubmission.TechnicianShiftId = rs.Id;
workordersubmission.SubmissionDate = DateTime.Now;
db.WorkOrderSubmissions.Add(workordersubmission);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ActivityRejectCodeId = new SelectList(db.ActivityRejectCodes, "Id", "RejectCodeId", workordersubmission.ActivityRejectCodeId);
ViewBag.Activities = GetActivities(activityId);
ViewBag.Workstations = GetWorkstationsByActivity(activityId, workstationId);
ViewBag.Platforms = GetPlatformsByWorkstation(activityId, workstationId, platformId);
ViewBag.Parts = GetPartsByPlatform(activityId, workstationId, platformId, partId);
ViewBag.StatusId = new SelectList(db.Status, "Id", "Name", workordersubmission.StatusId);
ViewBag.Technicians = GetTechnicians(techId);
ViewBag.Shifts = GetShiftsByTechnician(techId, shiftId);
ViewBag.WorkOrderId = new SelectList(db.WorkOrders, "Id", "WO", workordersubmission.WorkOrderId);
return View(workordersubmission);
}
//
// GET: /Submissions/Edit/5
public ActionResult Edit(int id = 0)
{
WorkOrderSubmission workordersubmission = db.WorkOrderSubmissions.Find(id);
if (workordersubmission == null)
{
return HttpNotFound();
}
var platformStageId = workordersubmission.PlatformStageId;
var technicianShiftId = workordersubmission.TechnicianShiftId;
// Get ActivityId, WorkstationId, PlatformId, PartId from PlatformStageId
var rs = (from ps in db.PlatformStages
join wa in db.WorkstationActivities on ps.WorkstationActivityId equals wa.Id
join pp in db.PlatformParts on ps.PlatformPartId equals pp.Id
where ps.Id == platformStageId
select new
{
ActivityId = wa.ActivityId,
WorkstationId = wa.WorkstationId,
PlatformId = pp.PlatformId,
PartId = pp.PartId
})
.FirstOrDefault();
ViewBag.Activities = GetActivities(rs.ActivityId);
ViewBag.Workstations = GetWorkstationsByActivity(rs.ActivityId, rs.WorkstationId);
ViewBag.Platforms = GetPlatformsByWorkstation(rs.ActivityId, rs.WorkstationId, rs.PlatformId);
ViewBag.Parts = GetPartsByPlatform(rs.ActivityId, rs.WorkstationId, rs.PlatformId, rs.PartId);
// Get TechnicianId, ShiftId from TechnicianShiftId
var rs2 = (from ts in db.TechnicianShifts
where ts.Id == technicianShiftId
select new //TechnicianShift
{
TechnicianId = ts.TechnicianId,
ShiftId = ts.ShiftId
})
.FirstOrDefault();
ViewBag.Technicians = GetTechnicians(rs2.TechnicianId);
ViewBag.Shifts = GetShiftsByTechnician(rs2.TechnicianId, rs2.ShiftId);
ViewBag.ActivityRejectCodeId = new SelectList(db.ActivityRejectCodes, "Id", "RejectCodeId", workordersubmission.ActivityRejectCodeId);
ViewBag.StatusId = new SelectList(db.Status, "Id", "Name", workordersubmission.StatusId);
ViewBag.WorkOrderId = new SelectList(db.WorkOrders, "Id", "WO", workordersubmission.WorkOrderId);
return View(workordersubmission);
}
//
// POST: /WorkorderSubmissions/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(WorkOrderSubmission workordersubmission)
{
if (ModelState.IsValid)
{
db.Entry(workordersubmission).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ActivityRejectCodeId = new SelectList(db.ActivityRejectCodes, "Id", "RejectCodeId", workordersubmission.ActivityRejectCodeId);
ViewBag.PlatformStageId = new SelectList(db.PlatformStages.OrderBy(p => p.Name), "Id", "Name", workordersubmission.PlatformStageId);
ViewBag.StatusId = new SelectList(db.Status, "Id", "Name", workordersubmission.StatusId);
ViewBag.TechnicianShiftId = new SelectList(db.TechnicianShifts, "Id", "Description", workordersubmission.TechnicianShiftId);
ViewBag.WorkOrderId = new SelectList(db.WorkOrders, "Id", "WO", workordersubmission.WorkOrderId);
return View(workordersubmission);
}
Below is the AJAX call:
$(function () {
// Code that triggers when there is a change in Activity drop down.
$('#ActivityId').change(function () {
var activityId = $(this).val();
var url = 'GetRejectCodesByActivityJson';
// Empty the Reject Code drop down list.
$('#ActivityRejectCodeId').empty();
// Empty the Workstation, Platform, Part drop downs.
$('#WorkstationId').empty();
$('#PlatformId').empty();
$('#PartId').empty();
$('.showhide-workstation').show();
// AJAX call that re-populate Reject Code drop down depending on the Activity selected.
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: { activityId: activityId },
success: function (codes) {
$('#ActivityRejectCodeId').append('<option value=""></option>');
$.each(codes, function (i) {
$('#ActivityRejectCodeId').append('<option value = "' + codes[i].Value + '">' + codes[i].Text + '</option>')
});
},
error: function (ex) {
$('#ActivityRejectCodeId').append('<option value=""></option>');
}
}); // END $.ajax() on GetRejectCodesByActivityJson
url = 'GetWorkstationsByActivityJson';
// AJAX call that re-populate Workstation drop down depending on the Activity selected.
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: { activityId: activityId },
success: function (codes) {
$('#WorkstationId').append('<option value=""></option>');
$.each(codes, function (i) {
$('#WorkstationId').append('<option value = "' + codes[i].Value + '">' + codes[i].Text + '</option>');
});
},
error: function (ex) {
$('#WorkstationId').append('<option value=""></option>');
}
}); // END $.ajax() on GetRejectCodesByActivityJson
}); // END $('#ActivityId').change()
// Code that triggers when there is a change in Workstation drop down.
$('#WorkstationId').change(function () {
var activityId = $('#ActivityId').val();
var workstationId = $(this).val();
var url = 'GetPlatformsByWorkstationJson';
// Empty the Platform, Part drop downs.
$('#PlatformId').empty();
$('#PartId').empty();
$('.showhide-platform').show();
// AJAX call that re-populate Platform drop down depending on the Workstation selected.
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: { activityId: activityId, workstationId: workstationId },
success: function (codes) {
$('#PlatformId').append('<option value=""></option>');
$.each(codes, function (i) {
$('#PlatformId').append('<option value = "' + codes[i].Value + '">' + codes[i].Text + '</option>');
});
},
error: function (ex) {
$('#PlatformId').append('<option value=""></option>');
}
}); // END $.ajax() on GetPlatformsByWorkstationJson
}); // END $('#WorkstationId').change()

jsTree not getting data from server

In my mvc application, I have used jsTree,
my view
#{
ViewBag.Title = "OnDemand";
}
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/jstree.min.js"></script>
<h2>OnDemand - Treeview</h2>
<div id="demo1">
</div>
<script type="text/javascript">
jQuery(function($) {
$("#demo1").jstree({
"json_data": {
"ajax": {
"type": "POST",
"dataType": "json",
"async": true,
"contentType": "application/json;",
"opts": {
"method": "POST",
"url": "/Treeview/GetAllNodes11"
},
"url": "/Treeview/GetAllNodes11",
"data": function (node) {
if (node == -1) {
return '{ "operation" : "get_children", "id" : -1 }';
}
else {
//get the children for this node
return '{ "operation" : "get_children", "id" : ' + $(node).attr("id") + ' }';
}
},
"success": function (retval) {
return retval.d;
},
}
},
"plugins": ["themes", "json_data"]
});
});
</script>
my controller
[HttpPost]
public JsonResult GetAllNodes11(string id)
{
List G_JSTreeArray = new List();
G_JSTree _G_JSTree = new G_JSTree();
_G_JSTree.data = "x1";
_G_JSTree.state = "closed";
_G_JSTree.IdServerUse = 10;
_G_JSTree.children = null;
_G_JSTree.attr = new G_JsTreeAttribute { id = "10", selected = false };
G_JSTreeArray.Add(_G_JSTree);
G_JSTree _G_JSTree2 = new G_JSTree();
var children =
new G_JSTree[]
{
new G_JSTree { data = "x1-11", attr = new G_JsTreeAttribute { id = "201" } },
new G_JSTree { data = "x1-12", attr = new G_JsTreeAttribute { id = "202" } },
new G_JSTree { data = "x1-13", attr = new G_JsTreeAttribute { id = "203" } },
new G_JSTree { data = "x1-14", attr = new G_JsTreeAttribute { id = "204" } },
};
_G_JSTree2.data = "x2";
_G_JSTree2.IdServerUse = 20;
_G_JSTree2.state = "closed";
_G_JSTree2.children = children;
_G_JSTree2.attr = new G_JsTreeAttribute { id = "20", selected = true };
G_JSTreeArray.Add(_G_JSTree2);
G_JSTree _G_JSTree3 = new G_JSTree();
var children2 =
new G_JSTree[]
{
new G_JSTree { data = "x2-11", attr = new G_JsTreeAttribute { id = "301" } },
new G_JSTree { data = "x2-12", attr = new G_JsTreeAttribute { id = "302" }, children= new G_JSTree[]{new G_JSTree{data = "x2-21", attr = new G_JsTreeAttribute { id = "3011" }}} },
new G_JSTree { data = "x2-13", attr = new G_JsTreeAttribute { id = "303" } },
new G_JSTree { data = "x2-14", attr = new G_JsTreeAttribute { id = "304" } },
};
_G_JSTree3.data = "x3";
_G_JSTree3.state = "closed";
_G_JSTree3.IdServerUse = 30;
_G_JSTree3.children = children2;
_G_JSTree3.attr = new G_JsTreeAttribute { id = "30", selected = true };
G_JSTreeArray.Add(_G_JSTree3);
return new JsonResult { Data = G_JSTreeArray, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
but it does not hitting the controller
what is the issue with this code?
data cannot be a function so dynamic data assignment based on selected node is not evaluated but you use assign url with a function to change parameter to pass to controller. you must use GET method to retrieve data from controller -
Try this
"json_data": {
ajax: {
"url": function (node) {
var url;
if (node == -1) {
url = "/Treeview/GetAllNodes11/?operation=get_children";
} else {
var id = $(node).attr("id");
url = "/Treeview/GetAllNodes11/?operation=get_children&id=" + id;
}
return url;
},
"type": "GET",
"dataType": "json",
"contentType": "application/json charset=utf-8",
},
},

Show highcharts for database data

I have tried to display a chart for database data but I'm having some trouble. I've tried using json to high charts but it's not working. Could someone please explain to me how to show axis as date and to call this on viewpage?
public List<CustomerAccount> ChartData(long customerID)
{
List<CustomerAccount> chart = new List<CustomerAccount>();
List<CustomerAccount> points = new CustomerAccountDBMgr().ChartAccount(customerID).FindAll(e => e.AccountName != "Others");
if (null == points || points.Count == 0)
return null;
var val = (from item in points select new { CreatedAt = item.CreatedAt, OpeningBalance = item.OpeningBalance }).ToList();
foreach (var data in val)
{
CustomerAccount objCustomer = new CustomerAccount()
{
CreatedAt = data.CreatedAt,
OpeningBalance = data.OpeningBalance
};
chart.Add(objCustomer);
}
return chart;
}
Model
public class Chart1
{
public DateTime CreatedAt { get; set; }
public Double? OpeningBalance { get; set; }
public List<CustomerAccount> ChartData()
{
PersonalizeBL business=new PersonalizeBL();
var CustomerID = PERFICSSession.GetCustomerID();
List<CustomerAccount>point=business.ChartData(CustomerID);
return point;
}
}
Controller
public ActionResult Chart1()
{
if (!PERFICSSession.IsValidSession())
return View("Login");
Chart1 model = new Chart1();
Highcharts chart = new Highcharts("chart")
.InitChart(new Chart { DefaultSeriesType = ChartTypes.Line })
.SetTitle(new Title { Text = "Database Data" })
.SetXAxis(new XAxis { Type = AxisTypes.Datetime })
.SetYAxis(new[]
{
new YAxis
{
Title = new YAxisTitle { Text = "Amount" },
GridLineWidth = 1
}
})
.SetSeries(new[]
{
new Series
{
Name = "OpeningBalance",
Data = new Data((model.ChartData()).Select(x=>new points{X=DotNet.Highcharts.Helpers.Tools.GetTotalMilliseconds(x.CreatedAt),Y=x.OpeningBalance}).ToArray())
}
});
return View("Chart1");
}
Finally i found answere for this issue. i would have return view which object i did created from highcharts. i wrongly returned the view page name.
public ActionResult Chart1()
{
chartModel model = new chartModel();
var data = model.chartPlots(Session);
Highcharts chart = new Highcharts("chart")
.InitChart(new Chart { DefaultSeriesType = ChartTypes.Line })
.SetTitle(new Title { Text = "Database Data" })
.SetXAxis(new XAxis { Type = AxisTypes.Datetime })
.SetYAxis(new[]
{
new YAxis
{
Title = new YAxisTitle { Text = "Amount" },
GridLineWidth = 1
}
})
.SetSeries(new[]
{
new Series
{
Name = "OpeningBalance",
Data = new Data(data.Select(x=>new points{X=DotNet.Highcharts.Helpers.Tools.GetTotalMilliseconds(x.CreatedAt),Y=x.OpeningBalance}).ToArray())
}
});
return View(chart);
}
return View(chart);
}

how can fill a grid with kendo ui

how can fill a grid with kendo.....
This is my controller
it`s work
public JsonResult listarporfecha([DataSourceRequest] DataSourceRequest request, string anio, string mes)
{
List<Reporte1Hist> reporte = new List<Reporte1Hist>();
DateTime fecha;
DateTime time;
short dia = 31;
short year = Convert.ToInt16(anio);
short m = Convert.ToInt16(mes);
// string date = anio + "-" + mes + "-" + dia;
DateTime fdate;
string MyString;
try
{
if (mes == null && anio == null)
{
fecha = DateTime.Now;
}
else
{
time = new DateTime(year, m, dia);
reporte = contexto.Reporte1Hist.Where(p => p.Fecha == time).ToList();
}
}
catch (Exception)
{
throw;
}
return Json(new[] { reporte }.ToDataSourceResult(request, ModelState));
}
and this is my jquery, it doesn't work,
var url = '#Url.Action("listarporfecha","Home")';
$.post(url, { anio: year, mes: month }, function (data) {
$("#Grid").kendoGrid({
dataSource: {
transport: {
read: {
type:"POST",
url: '#Url.Action("listarporfecha","Home")',
dataType: "json",
data:data
}
}
// schema: {
// data: "data"
//}
}
});
});

How to update Chosen dropdownlist's items(cascade dropdownlist)?

I use Chosen plugin. I want to refresh Category (Chosen) dropdownlist, when change Section dropdownlist.
Here is view:
#model CategoryInputModel
#Html.DropDownListFor(model => model.SectionId, ViewBag.SectionList as IEnumerable<SelectListItem>, new { id = "SectionId" })
#Html.ListBoxFor(model => model.CategoryIdSet, ViewBag.AllCategoryList as MultiSelectList
, new
{
#class = "chzn-select",
data_placeholder = "Choose Categories...",
#style = "width : 500px;",
id = "CategoryIdSet"
})
CategoryInputModel is like:
public class CategoryInputModel
{
public string Name { get; set; }
public int SectionId{ get; set; }
public List<int> CategoryIdSet{ get; set; }
}
I can create cascade dropdownlist for simple lists, but could not create it for multiple select. I tried this :
<script type="text/javascript">
$(function () {
$("#SectionId").change(
function () {
loadLevelTwo(this);
});
loadLevelTwo($("#SectionId"));
});
function loadLevelTwo(selectList) {
var selectedId = $(selectList).val();
$.ajax(
{
url: "#Url.Action("GetCategoriesBySectionId", "Project")",
type: "GET",
data: { id: selectedId },
success: function (data) {
$("#CategoryIdSet").html($(data).html());
},
error: function (xhr) {
alert("Something went wrong, please try again");
}
});
}
</script>
In controller:
public ActionResult GetCategoriesBySectionId(int id)
{
var result = MyService.GetCategoriesBySectionId(id);
// **its problem to create partial view that return chosen dropdownlist I need**
}
How can I create cascade Chosen dropdownlist?
I think you need to add a little more to your ajax callback. I replaced success method with done. Try this, it works for me:
function loadLevelTwo(selectList) {
var selectedId = $(selectList).val();
$.ajax(
{
url: "#Url.Action("GetCategoriesBySectionId", "Project")",
type: "GET",
data: { id: selectedId },
error: function (xhr) {
alert("Something went wrong, please try again");
}
}).done(function (data) {
$("#CategoryIdSet").children().each(function (index, option) {
$(option).remove();
});
//blank option
var items = "<option selected value=\"\"></option>";
$.each(data,
function () {
items += "<option value=\"" + this[0] + "\">" + this[1] + "</option>";
});
$("#CategoryIdSet").html(items)
$("#CategoryIdSet").trigger("liszt:updated");
$("#CategoryIdSet").change();
});
}
controller action could look like this:
public ActionResult GetCategoriesBySectionId(int id)
{
var result = MyService.GetCategoriesBySectionId(id);
//build JSON.
var modelDataStore = from m in result
select new[] { m.YourValueProperty.ToString(),
m.YourTextProperty };
return Json(modelDataStore, JsonRequestBehavior.AllowGet);
}

Resources