I have been working with charts today And I think that i finaly found a way for it all to work but I encountered an issue that I don't know how to pass.
Create my Charts in my controller:
foreach (var m in model[0].HistoryValues)
{
var chart = new Chart(width: 300, height: 200)
.AddSeries(
chartType: "bar",
xValue: new[] { "Server", "Db", "Tickets" },
yValues: new[] { m.ServerPerformance, m.Databaseperformance, m.SoldTicketsLastUpdate })
.GetBytes("png");
m.Bytes = chart;
//m.ChartFile = File(chart, "image/bytes");
};
now I want to display them as Images in the view:
#foreach (var m in Model[0].HistoryValues)
{
<img src="#Html.Action("getImage", "OverWatch", new { byte[] Mybytes= m.Bytes })" alt="Person Image" />
}
but im getting:
Invalid anonymous type member declarator. Anonymous type members must
be declared with a member assignment, simple name or member access.
getImage method:
public FileContentResult getImage(byte[] bytes)
{
return new FileContentResult(bytes, "image/jpeg");
}
How do I solve this?
In an anonymous type you dont define the variable type byte[]. It works it out itself based on the type of m.Bytes
#foreach (var m in Model[0].HistoryValues)
{
<img src="#Html.Action("getImage", "OverWatch", new { Mybytes= m.Bytes })" alt="Person Image" />
}
Related
I'm using this plugin, to make an autocomplete field inside a form to submit. It's all ok except when I submit the form, the field passed to the controller in the model is null. I don't know how to return the data I obtained.
That's my code html:
#Html.TextBoxFor(m => m.Team, new { #type = "text", id = "team", Name = "query", #class = "form-control", placeHolder = "Team (Ej -> Barcelona)", autocomplete = "off" })
JS code:
$('#team').typeahead({
ajax: "/Home/AutocompleteTeam",
responseText: [
$('#team').val()
]
});
C# code:
public ActionResult AutocompleteTeam(string query)
{
List<string> teams = new List<string>();
List<TeamServiceModel> teamsService = teamService.ListTeamsByQuery(query);
foreach (var team in teamsService)
{
if(team.Name.Equals("DEFAULT"))
{
continue;
}
else
{
teams.Add(team.Name);
}
}
return Json(teams, JsonRequestBehavior.AllowGet);
}
The service which is returning the list I'm filtering by the query is working.
Typeahead already filters result. You can make an ajax call to get all teams(return an array) and set 'local' field in typeahead with array values.
See more here http://www.bootply.com/ljIOxm3qDi
A PartialView contains a model Foo with a List<Bar>. Each Bar item contains two properties, BarA (string) and BarB (decimal).
I am trying to render a Chart in that partial view, but for that to work I need to call an action on the same Controller and pass the result to an <img /> element. To render the chart, I need the collections of BarA and BarB to format the data.
So I'm trying with something like this:
Controller
public void GenerateChart(List<Bar> model)
{
var chart = new System.Web.Helpers.Chart(400, 200)
.AddTitle("Title")
.AddSeries(
name : "name",
xValue : model.Select(m => m.BarA).ToArray(),
yValues : model.Select(m => m.BarB).ToArray())
.Write();
}
Partial View
RouteValueDictionary rvd = new RouteValueDictionary();
for (int i = 0; i < Model.Bars.Count; ++i)
{ rvd.Add("model[" + i + "]", Model.Bars[i]); }
<img src="#Url.Action("GenerateChart", rvd)" />
The problem with this is that even though the model object contains the three items it should contain, these are null.
I also tried to use the ViewBag, like this:
ViewBag.BarA = Model.Bars.Select(m => m.BarA).ToArray();
ViewBag.BarB = Model.Bars.Select(m => m.BarB).ToArray();
With this on the controller side
public void GenerateChart()
{
var chart = new System.Web.Helpers.Chart(400, 200)
.AddTitle("Title")
.AddSeries(
name : "name",
xValue : ViewBag.BarA,
yValues : ViewBag.BarB)
.Write();
}
But both arrays are null. I've also tried a few different ideas but I'm not able to get the information I need.
To triple-check (the data is shown fine in the view) that the data is correct, I changed to this:
#{
string[] barAs = Model.Select(m => m.BarA).ToArray();
decimal[] barBs = Model.Select(m => m.BarB).ToArray();
ViewBag.BarAs = barAs; // this has 3 items with the expected data
ViewBag.BarBs = barBs; // this also works
}
<img src="#Url.Action("GenerateChart")" />
string[] BarAs = ViewBag.BarAs; // this assigns null
decimal[] BarBs = ViewBag.BarBs; // this also assigns null
It seems you don't really understand how MVC works. I encourage you to spend some time going through all the tutorials at http://asp.net/mvc to familiarize yourself with the framework. Namely, it seems you're trying to approach a lot of this as if you were in the world of Web Forms. MVC is an entirely different beast.
First, Html.Action cannot return a full image, because all it's going to do is just dump the return value to the HTML being generated, and you can't embed a binary object directly in HTML.
Second, even if you could, you can't use that as the src for an img tag. The src must be a string, namely a URL, point to a location of an image.
So, in order to achieve this. You will need a full action that returns a proper response as an image. Then, you can simply link your image src to the route that hits this action.
public ActionResult GenerateChart(List<Bar> model)
{
var chart = new System.Web.Helpers.Chart(400, 200)
.AddTitle("Title")
.AddSeries(
name : "name",
xValue : model.Select(m => m.BarA).ToArray(),
yValues : model.Select(m => m.BarB).ToArray())
.GetBytes("jpeg");
return File(chart, "image/jpeg");
}
Then,
<img src="#Url.Action("GenerateChart", new { model = rvd })" alt="" />
Now, you're just link to a URL. That URL maps to a route that hits your GenerateChart action, which then returns an actual image - same as if you directly linked to a physical image. Now, the browser can properly render the img tag to the page.
Passing a complex type to actions via GET request is technically bloody thing so I do not know if this solution fits your needs you can follow up the method below;
Your action will recieve model as serialized string and you have to Deserialize it to your model
public ActionResult GenerateChart(string modelAsString)
{
List<Bar> model = new List<Bar>();
model = JsonConvert.DeserializeObject<List<Bar>>(modelAsString);
var chart = new System.Web.Helpers.Chart(400, 200)
.AddTitle("Title")
.AddSeries(
name: "name",
xValue: model.Select(m => m.BarA).ToArray(),
yValues: model.Select(m => m.BarB).ToArray())
.GetBytes("jpeg");
return File(chart, "image/jpeg");
}
Then you need to call your action via querystring like ?modelAsString={jsonData}
The example URL I use to process data : http://localhost:18681/Home/GenerateChart/?modelAsString=[{%22BarA%22:%22barAData%22,%22BarB%22:1.1},{%22BarA%22:%22barAData2%22,%22BarB%22:441.14},{%22BarA%22:%22barAData43%22,%22BarB%22:44.1}]
You should create your <img> URLs via serializing your model which ready on the page's action which you use <img>s.
I have tested a dummy data you can see output below;
PS: for creating dummy data I used the method below;
public ActionResult DummyData()
{
List<Bar> model = new List<Bar>();
model.Add(new Bar() { BarA = "barAData", BarB = 1.1m });
model.Add(new Bar() { BarA = "barAData2", BarB = 441.14m });
model.Add(new Bar() { BarA = "barAData43", BarB = 44.1m });
return Json(model, JsonRequestBehavior.AllowGet);
}
And I wonder too if any more efficient way to do this via get request.
Hope this helps!
I'm looking for a solution for this for 2 days already and can't find the answer, everything I find doesn't work so I thought somebody here might help.
I have a chart that I've managed to call from View with Url.Action like this:
<img src="#Url.Action("DrawPieChart")"/>
but I don't know how to pass the value of the parameter(countryName) through Url.Action so I can pass it through controller and finally use it in AnalyzerData.class
Here is the controller: WebTrafficController
public class WebTrafficController : Controller
{
public ActionResult WebTraffic()
{
AnalzyerData analyzerData = new AnalzyerData();
//main actionResult that shows stuff not important for this question
return View(analyzerData);
}
public ActionResult DrawPieChart(string countryName)
{
AnalzyerData analyzerData = new AnalzyerData();
return PartialView(analyzerData.getChart(countryName));
}
}
Class: AnalyzerData
public class AnalzyerData
{
public Chart chartImg { get; set; }
public Chart getChart(string countryName)
{
cWebTrafficDb checkUserStatsWrapper = new cWebTrafficDb();
checkUserStatsWrapper.cmd.CommandText = string.Format("select user_browser, count(*) from user_stats where User_country = '{0}' group by user_browser", countryName);
//checkUserStatsWrapper.cmd.CommandText = string.Format("select user_browser, count(*) from user_stats group by user_browser");
MySqlDataReader reader = checkUserStatsWrapper.cmd.ExecuteReader();
List<object> result1 = new List<object>();
List<object> result2 = new List<object>();
while (reader.Read())
{
result1.Add(reader.GetString(0));
result2.Add(reader.GetString(1));
}
chartImg = new Chart(width: 350, height: 350)
.AddTitle("Naslov")
.AddSeries(
name: "Employee",
chartType: "Pie",
xValue: result1,
yValues: result2)
.Write();
return chartImg;
}
View: Webtraffic.cshtml
#model WebTraff.Models.AnalzyerData
#{
ViewBag.Title = "WebTraffic";
}
<div class="inline">
<img src="#Url.Action("DrawPieChart","countryName", new { countryName = "Croatia" })"/>
</div>
P.S. if this isn't possible please tell me how to do this, I've tried a few different methods and I couldn't get it work
There's one thing you can try here.
Replace this :
<img src="#Url.Action("DrawPieChart","WebTraffic", new { countryName = "Croatia" })"/>
With this :
<img src="#Url.Action("DrawPieChart","WebTraffic", new { #countryName = "Croatia" })"/>
Or you can also try it like this :
#Url.Action("DrawPieChart", "WebTraffic", new { #countryName = "Croatia" })
Try putting the # symbol before the parameter name and make sure the parameter name remains identical on both sides.
Hope this helps.
Not sure if this was ever resolved but I just came across the same issue. I found out that using your code of:
<img src="#Url.Action("DrawPieChart","countryName", new { countryName = "Croatia" })"/>
passed the browser the following html
<img src="/countryName/DrawPieChart?countryName=Croatia">
Changing your code by simply dropping the first "countryName" to match the following:
<img src="#Url.Action("DrawPieChart", new { countryName = "Croatia" })"/>
worked for me... Hope this helps!
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();
}
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")" />