Call controller from aspx - c#

This is my first time trying to implement a project using MVC, and I am kind of lost.
I have a view, named chart.aspx
and a controller which has the function
public ActionResult GetChartImage()
{
var key = new Chart(width: 300, height: 300)
.AddTitle("Employee Chart")
.AddSeries(
chartType: "Bubble",
name: "Employee",
xValue: new[] { "Peter", "Andrew", "Julie", "Dave" },
yValues: new[] { "2", "7", "5", "3" });
return File(key.ToWebImage().GetBytes(), "image/jpeg");
}
I want to call that from my aspx page, in order to show a chart.
How I can do that?

In your view add the following:
<img src="<%= Html.Action("GetChartImage", "YourControllerName") %>" />

Try this,Use Url.action in your img tag src
and also need to change ActionResult to FileContentResult . But it does not a matter .
<img src="#Url.Action("GetChartImage", "YourControllerName")" />

Related

Embedding a pie chart in ASP.NET (Razor syntax)

I'm fairly new to ASP.NET (have been coding in WPF a long time, but new to ASP) and I'm trying to create a dashboard application that shows four pie charts. I've followed the instructions on this link, but I either get a chart on the entire page, or a broken image (as if the <img> source is not valid)
Can someone please explain to me how to achieve this behavior? I just want to display a simple pie chart on my page, that's it.
Thanks! (and sorry if this is a duplicated post, I've found other similar questions but none using the Razor syntax)
EDIT - Here's my code:
Index.cshtml:
<!DOCTYPE html>
<html>
<head>
<title>Chart Example</title>
</head>
<body>
<h1>Chart Example</h1>
<p>
The following chart is generated by the <em>ChartView.cshtml</em> file, but is shown
in this page.
</p>
<p><img src="ChartView.cshtml" /> </p>
</body>
</html>
My ChartView.cshtml: (located in the same folder as Index.cshtml)
#{
var myChart = new Chart(600, 400)
.AddTitle("Employees")
.AddSeries(chartType: "column",
xValue: new[] { "Peter", "Andrew", "Julie", "Mary", "Dave" },
yValues: new[] { "2", "6", "4", "5", "3" });
if (myChart != null)
{
myChart.Write();
}
}
This is what I get on the browser:
You can't return a .cshtml file (unless you fiddle dangerously with various internal settings - not recommended).
You should be pointing to an action.
The easiest way to test this is by opening the src directly in the browser - in this case "ChartView.cshtml" and you should get a 404.
You'll need to add an action to your controller that returns the view.
public HomeController : Controller
{
public ActionResult ChartView()
{
return View();
}
then
<img src='#Url.Action("ChartView", "Home")' alt="Chart"/>
You can test this by opening in the browser:
/Home/ChartView
(this assumes that ChartView.cshtml is in the folder "Views/Home")
As you're new to MVC, quick explanation. There a 'routeConfig.cs' which routes incoming urls to an action(method) on a controller(class). The controller loads the view (cshtml) and applies all the server-side code then returns the rendered html to the user.
You do not navigate directly to cshtml pages but navigate instead to actions via the url.
The default route config gives you urls such as:
http://[site]/[controller]/[action]
Note that [controller] does not include "Controller", so "HomeController" becomes "/Home/"
Also, by convention, if you don't specify a view name in 'View()' then it will look in your solution folder "/Views/[controller]/[action].cshml' (among other locations such as '/Views/Shared/[action].cshtml' (also configurable, but these are the defaults).
you easely can combine
http://morrisjs.github.io/morris.js/index.html
in mvc (razor syntax)
or you can use chart helper
http://www.asp.net/web-pages/overview/data/7-displaying-data-in-a-chart
change to:
#{
var myChart = new Chart(600, 400)
.AddTitle("Employees")
.AddSeries("SomeName",chartType: "Pie",
xValue: new[] { "Peter", "Andrew", "Julie", "Mary", "Dave" },
yValues: new[] { "2", "6", "4", "5", "3" });
if (myChart != null)
{
myChart.Write();
}
}
you have to lunch it in iis or some development server

JQGrid in MVC Not Loading the Grid

I have an MVC Edit View that contains Contact Information that is of course editable. In that view I want to add a section containing a JQGrid allowing the user to CRUD notes for the Contact but my grid is not loading with data nor is the method on the controller being called. Can anyone give me any insite?
View Code
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-info">
Contact Note</h3>
</div>
<div class="panel-body">
<div class="scrollableContainer" style="margin-top: -10px;">
<table id="JQGrid1"></table>
<div id="JQGrid1_pager"></div>
</div>
</div>
</div>
<script>
$("#JQGrid1").jqGrid({
url: '#Url.Action("GetNotes", "Contact")',
mtype: "GET",
datatype: "json",
page: 1,
jsonReader: { id: document.getElementById('SelectedContact_ContactID').value },
prmNames: { id: document.getElementById('SelectedContact_ContactID').value },
colNames: ["Id", "ContactId", "Note", "Date Created", "Created By"],
colModel: [
{ key: true, width: 50, name: "ID", hidden: false },
{ width: 60, name: "ContactID", hidden: false },
{ width: 460, name: "Note", hidden: false },
{ width: 160, name: "DateCreated",
formatter: "date", formatoptions: { srcformat: "m/d/Y h:i:s A", newformat: "mm-dd-yyyy" }, hidden: false },
{ width: 160, name: "CreatedBy", hidden: false },
],
height: "auto",
caption: "Notes",
rowNum: 5,
pager: "#JQGrid1_pager",
});
</script>
Controller Code
[HttpGet]
public JsonResult GetNotes(int id)
{
var gridModel = new ContactNotesJQGridModel();
var resultset = _contactNoteRepository.GetNotes(id);
return gridModel.ContactNotesGrid.DataBind(resultset.AsQueryable());
}
GridModel Class
public class ContactNotesJQGridModel
{
public JQGrid ContactNotesGrid { get; set; }
public ContactNotesJQGridModel()
{
ContactNotesGrid = new JQGrid
{
Columns = new List<JQGridColumn>()
{
new JQGridColumn {DataField = "ID", PrimaryKey = true},
new JQGridColumn {DataField = "ContactId"},
new JQGridColumn {DataField = "Note"},
new JQGridColumn {DataField = "DateCreated"},
new JQGridColumn {DataField = "CreatedBy"},
}
};
}
Then in the Edit Call for the Contact in the Contact Controller I set model.ContactNotesGrid = new ContactNotesJQGridModel GetNotes(int id) is never executed eventhough it's specified in the jquery.
You should use postData to add custom parameter to the server response:
postData: { id: 11 }
or
postData: {
id: function () {
return document.getElementById('SelectedContact_ContactID').value;
}
}
You need additionally modify the code of the server to use something like
return Json(someObjectWithReturnedData, JsonRequestBehavior.AllowGet);
I recommend you to add loadError callback to the list of jqGrid option (see the answer) and add gridview: true and autoencode: true option to jqGrid.
P.S. About the errors like "unable to get value of the property integer", "unable to get value of the property decimalSeperator". You should verify that you included locale file like i18n/grid.locale-en.js before jquery.jqGrid.min.js (see the documentation).
Try this :
Check 1:
Move your Jquery script inside the document ready event:
$( document ).ready(function() {
console.log( "ready!" );
});
Check 2:
Check weather your server request having any problem or not:
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Response.Clear();
}
Add the above code in your Global.asax and make sure there is no exception during the call. (Put Break point and check)
Check 3:
Watch your browser console log (F12). If there is any exception log please provide that.
Check 4:
Make sure if the call is success the expected json format is valid or not. In most of the cases it will be the major cause.
The above's are just my guesses / this is what i do first, if i have a prob. :)

display charts using MVC, .net c#

I'm trying to display some charts on my mvc app but I'm having some errors. I'm developing in localhost. I have one cshtml file named ReportChart
#{
var myChart = new Chart(width: 600, height: 400)
.AddTitle("Chart Title")
.AddSeries(
name: "Employee",
xValue: new[] { "Peter", "Andrew", "Julie", "Mary", "Dave" },
yValues: new[] { "2", "6", "4", "5", "3" })
.Write();
}
and another file that use that chart:
<body>
<h1>Chart Example</h1>
<p>The following chart is generated by the <em>ReportChart.cshtml</em> file:</p>
<p><img src="ReportChart.cshtml" alt="Cricketers" /> </p>
The only problem is that the webpage doesn't display any image :/
No it won't work in MVC. You should create chart in the controller action method:
//I CUT THE CODE WHERE I construct string[] t1 and int[] t2 these are just arrays
public ActionResult EfficiencyChart(string pid) {
var myChart = new Chart(width: 1000, height: 600)
.AddTitle("Employee's Efficiency")
.AddSeries(
name: "Employee",
xValue: t2,
yValues: t1)
.Write();
myChart.Save("~/Content/chart" + user.Id, "jpeg");
// Return the contents of the Stream to the client
return base.File("~/Content/chart" + user.Id, "jpeg");
}
Then in the Razor view:
<img src="#Url.Action("EfficiencyChart", "NAME_OF_THE_CONTROLLER", new { pid = #Model.Id })" />
try it,
<p><img src="#Url.Action("ReportChart")" alt="Cricketers" /> </p>
public ActionResult ReportChart()
{
return PartialView();
}

JqGrid is displayed with columns and no json data

i am trying to bind JSON data to jqgrid. But, i am not getting any data.
here, is my code:
$(function () {
$("#list").jqGrid({
url:'<%:Url.Action("LoadData","Home")%>',
datatype: "JSON",
mtype: "GET",
colNames: ["sid","sname"],
colModel: [
{ name: "sid", width: 55,align:"center"},
{ name: "sname", width: 90,align:"center"},
],
jsonReader: {
repeatitems: false
},
pager: "#pager",
rowNum: 10,
rowList: [10, 20, 30],
viewrecords: true,
gridview: true,
autoencode: true,
caption: "My first grid"
});
});
I am using it in Asp.net MVC Application.
I am able to hit the controller and get the JSON data..but i was unsucessful in displaying data to grid.
I am getting proper json o/p from controller.
My Controller is:
public JsonResult LoadData()
{
var Data= new DataTable();
Data= DataModel.LoadData();
var JsonData = JsonConvert.SerializeObject(Packages, Formatting.Indented);
return Json(new
{
JsonData
}, JsonRequestBehavior.AllowGet);
}
I think there is error in my JQgrid jquery code. Firtly, i want to implement the jqgrid with minimal configuration.
The JSON response i am getting is:
[
{
"sid": 2,
"sname": "ABC"
},
{
"sid": 3,
"sname": "XYZ"
},
{
"sid": 4,
"sname": "CBA"
},
{
"sid": 5,
"sname": "IIT"
},
{
"sid": 6,
"sname": "NIT"
}
]
This is my HTML Structure:
<table id="list">
</table>
<div id="pager"></div>
I removed the duplicates from the data i am fetching..
The JSON result, i have checked in Text Visualizer of Visual Studio.Its fine..
Please help..
I suppose that the reason of your problem is the usage of JsonConvert.SerializeObject. You should return object instead of string. Try to use
return Json(Packages, JsonRequestBehavior.AllowGet);
directly.
Not sure you have js code in .js file on in .aspx file.
Anyway try this and check the request/response with Firefox/Chrome console
$(function () {
$("#list").jqGrid({
url:/Home/LoadData/,
datatype: "json",
mtype: "GET",
colNames: ["sid","sname"],
colModel: [
{ name: "sid", width: 55,align:"center"},
{ name: "sname", width: 90,align:"center"},
],
pager: "#pager",
rowNum: 10,
rowList: [10, 20, 30],
viewrecords: true,
gridview: true,
caption: "My first grid"
});
});
HTML
<table id="list"></table>
<div id="pager"></div>

html.actionlink in jqgrid

i am trying to get a column with an html.actionlink into a jqgrid? any ideas ?
any other grid suggestions welcome too. ta
don't need to use telerik for column with an html.actionlink. We can use this in jqGrid itself
. Below are the code.
{ name: 'Restart',
formatter: function (cellvalue, options, rowObject) {
var x = '#Html.ActionLink( "Restart", "Restart","Dashboard",new { requestId ="myId" }, new {#style="color:Blue;font-weight:bold;", onclick = "return confirm('Are you sure to Restart?');" })';
return x.replace("myId",rowObject[8]);
}, align: 'left', width: 100
}
or
{ name: 'Restart',
formatter: function (cellvalue, options, rowObject) {
return '#Html.ActionLink( "Restart", "Restart","Dashboard",new { requestId ="yourId" }, new {#style="color:Blue;font-weight:bold;", onclick = "return confirm('Are you sure to Restart?');" })';
}, align: 'left', width: 100
}
Its working fine for me
You can try telerik extensions for asp.net mvc. i used it personally and found it really good.
here is link to demo page. its open source

Categories