I use stimulsoft in asp.net mvc for reporting ...
I want to bind a dynamic datatable/dataset into my report , So I search for it and
There is my code
View:
#Html.StiMvcViewerFx(new StiMvcViewerFxOptions()
{
ActionGetReportSnapshot = "GetReportSnapshot",
Width = Unit.Percentage(100),
Height = Unit.Pixel(700),
Zoom = 100
})
Controller:
public ActionResult GetReportSnapshot()
{
var report = new StiReport();
//a blank file .mrt
report.Load( Server.MapPath("~") + "Content/StimulReport/Data/Surveys/Report/Report.mrt" );
var dt = new DataTable("Text");
dt.Columns.Add("Name");
for (int i = 0; i < 100; i++)
{
dt.Rows.Add(i);
}
var dataSet = new DataSet("Demo");
dataSet.Tables.Add(dt);
report.RegData(dataSet);
return StiMvcViewerFxHelper.GetReportSnapshotResult(report);
}
But the Report Just Show A Blank Page:
For windows application it's work correctly but in web it's not
Please help me
Try to use next code:
report.RegData(dataSet);
return StiMvcViewerFxHelper.GetReportSnapshotResult(this.Request, report);
Related
I want to port this Spring MVC to .NET MVC. This Spring MVC can handle any submissions because I am a map:
#RequestMapping(value = "/invokeFormStrSubmit.do", method = RequestMethod.POST)
ModelAndView addCustomer2(HttpServletRequest request, HttpServletResponse response) {
java.util.Map<java.lang.String,java.lang.String[]> formData = request.getParameterMap();
This works nicely in Spring MVC.
How do we do this same in .NET MVC? I can read the parameters when I know the form fields.
Thank you for your help...
Request.Params is a NameValue collection of everything submitted in the form. See here:
HttpRequest.Params
You can use NameValueCollection -
a collection of associated String keys and String values that can be accessed either with the key or with the index.
public System.Collections.Specialized.NameValueCollection Params { get; }
See below how to loop through the Params property for a page and how to display each key/value pair.
string paramInfo = "";
NameValueCollection pColl = Request.Params;
for(int i = 0; i <= pColl.Count - 1; i++)
{
paramInfo += "Key: " + pColl.GetKey(i);
string[] pValues = pColl.GetValues(i);
for(int j = 0; j <= pValues.Length - 1; j++)
{
paramInfo += "Value:" + pValues[j];
}
HTTPRequest.Params is not defined for HTTPRequest that is part of Microsoft.AspNetCore.Http namespace.
My objective was to build a COntroller that can handle form fields from an unknown form. It could be a JQuery Mobile Form with different fields. Since there are different fields - we cannot use a model.
I got this working with HTTPRequest.Form:
public IActionResult HandleSubmission()
{
// NameValueCollection coll;
try
{
var address = HttpContext.Connection.RemoteIpAddress;
var userAgent = Request.Headers["User-Agent"].FirstOrDefault();
IFormCollection userdata = Request.Form;
int myCount = userdata.Count;
foreach (var item in userdata.Keys)
{
String yy = "5";
String uu= item.ToString();
Microsoft.Extensions.Primitives.StringValues ttt;
userdata.TryGetValue(uu, out ttt);
}
}
catch (Exception w)
{
Console.Write(w.StackTrace);
}
On an asp.net mvc page, I have a Kendo UI grid and a Kendo UI treeview. The treeview has checkboxes and the treeview has two tier data. Then once the grid is populated, I want to loop through the rows, find the corresponding id, then loop through the treeview and find the node with the same id and make it checked. The following is my code:
Grid code:
dataBound: function () {
var rows = this.tbody.children();
var dataItems = this.dataSource.view();
for (var i = 0; i < dataItems.length; i++) {
kendo.bind(rows[i], dataItems[i]);
bindCheckboxToId(dataItems[i].ID);
}
}
The javascript function to set the treeview node to be checked:
function bindCheckboxToId(id) {
var treeView = $("#treeview").data("kendoTreeView");
var myNodes = treeView.dataSource.view();
for (var i = 0; i < myNodes.length; i++) {
var children = myNodes[i].children.view();
alert(children.length);
if (children) {
for (var j = 0; j < children.length; j++) {
if (children[j].id === id) {
children[j].set("checked", true);
}
}
}
}
The problem is that, the children.length always comes as 0, although each parent node has two child nodes.
Thanks
We have to force the tree view to load the child nodes. The following is the updated code:
function bindCheckboxToId(id) {
var treeView = $("#treeview").data("kendoTreeView");
var myNodes = treeView.dataSource.view();
for (var i = 0; i < myNodes.length; i++) {
myNodes[i].load();
var children = myNodes[i].children.view();
//alert(children.length);
if (children) {
for (var j = 0; j < children.length; j++) {
if (children[j].id === id) {
children[j].set("checked", true);
}
}
}
}
}
I'm on my smartgwt project having issue in listgrid.
my listgrid having data come from server side, and user allow to edit any record from that grid.
searchGrid.setAutoFetchData(true);
searchGrid.setDataSource(searchDS);
searchGrid.setAlwaysShowEditors(true);
When I try to edit any cell in grid and try to loop through all record from grid, it doesn't give me latest updated cell which I edited.
I use below code for fetching all records from my listgrid.
private String getGridDetails() {
RecordList records = searchGrid.getRecordList();
Document doc = XMLParser.createDocument();
Element rootElement = doc.createElement("ROOT");
doc.appendChild(rootElement);
for (int i = 0; i < records.getLength(); i++) {
Record rec = records.get(i);
Element row = doc.createElement("ROW");
for (String str : rec.getAttributes()) {
String propertyVal = rec.getAttributeAsString(str);
if (propertyVal != null
&& propertyVal.equalsIgnoreCase("") != true) {
Element columnElement = doc
.createElement(str.toUpperCase());
columnElement.appendChild(doc.createTextNode(propertyVal));
row.appendChild(columnElement);
}
}
rootElement.appendChild(row);
}
return doc.toString();
}
If you want to get every edited and unedited record, you may loop one by one:
public Record[] getData(ListGrid grid)
{
RecordList data = new RecordList();
for (int i = 0; i < grid.getTotalRows(); i++)
data.add(grid.getEditedRecord(i));
return data.duplicate();
}
But if you just want to retrieve the edited records, try the following snippet:
public static Record[] dameDatosLocalesEditedRows(ListGrid grid)
{
RecordList data = new RecordList();
int[] edited = grid.getAllEditRows();
for (int i = 0; i < edited.length; i++)
data.add(grid.getEditedRecord(edited[i]));
return data.duplicate();
}
ISSUE:
I have an asp.net mvc 3 app. I'm using EF 4.1 and trying out jqGrid. I'm trying to get data for my jqGrid using the GridData method below. I get the following error on the group of data starting at 'var jsonData = new...'. Any ideas?
ERROR:
{"The array type 'System.String[]' cannot be initialized in a query result.
Consider using 'System.Collections.Generic.List`1[System.String]' instead."}
GridData Method:
public JsonResult GridData(string sidx, string sord, int page, int rows)
{
var result = from a in db.t_harvest_statistics_elk
where a.year == "2008" && a.unit_number == 1
orderby a.id
select a;
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
int totalRecords = result.Count(); // context.Questions.Count();
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
var questions = result.Skip(pageIndex * pageSize).Take(pageSize);
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = (
from question in questions
select new
{
i = question.id,
cell = new string[] { SqlFunctions.StringConvert((double)question.id), SqlFunctions.StringConvert((double)question.total_rec_days), question.year }
}).ToArray()
};
return Json(jsonData);
}
HERE IS AN EXAMPLE THAT DOES WORK
public JsonResult DynamicGridData(string sidx, string sord, int page, int rows)
{
var context = new HaackOverflowDataContext();
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
int totalRecords = context.Questions.Count();
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
var questions = context.Questions.OrderBy(sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize);
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = (
from question in questions
select new
{
i = question.Id,
cell = new string[] { question.Id.ToString(), question.Votes.ToString(), question.Title }
}).ToArray()
};
return Json(jsonData);
}
The easiest way to fix the code will be to use something like the following
// to be able to use ToString() below which is NOT exist in the LINQ to Entity
// so we should get the data from the database and save the result locally before
// the next step. One can use .ToList() or to .AsEnumerable(), but one should
// choose only the fields of questions which we will need later
var queryDetails = (from item in questions
select new { item.id, item.total_rec_days, item.year }).ToList();
var jsonData = new {
total = totalPages,
page,
records = totalRecords,
rows = (
from question in queryDetails
select new
{
id = question.Id,
cell = new [] {
question.Id.ToString(),
question.total_rec_days.ToString(),
question.year.ToString()
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
Your current code contain some small problems like the usage of i = question.id instead of id = question.id.
I would recommend you to read the answer and download the demo from the answer which contains more recent and extended code.
var jsonData = new {
total = totalPages,
page,
records = totalRecords,
rows = (
from question in queryDetails
select new
{
id = question.Id,
cell = new IComparable[]{
question.Id.ToString(),
question.total_rec_days.ToString(),
question.year.ToString()
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
Can you try modifying your code like :
rows = (
from question in questions.AsEnumerable() //AsEnumerable() is added to switch to LINQ to Entites to eager load the data.
select new
{
i = question.id,
cell = new string[] { SqlFunctions.StringConvert((double)question.id), SqlFunctions.StringConvert((double)question.total_rec_days), question.year }
}).ToArray()
Because the MSDN says that : "You cannot call this function directly. This function can only appear within a LINQ to Entities query." (Though the next line is little confusing in documentation)
You can't use custom functions inside direct queries to you database. Instead you can do something like this:
rows = questions.AsEnumerable()
//or select just that you want questions.Select(q=> new {g.Id, q.Votes,q.Title})
.Select(p=> new {
id = p.Id,
cell = new string[] { SqlFunctions.StringConvert((double)p.id), SqlFunctions.StringConvert((double)p.total_rec_days), p.year }
}).ToArray()
That should work.
I have a MVC application, which creates a Chart in the business logic like this:
StatisticsModel.Chart.Width = 150
StatisticsModel.Chart.Height = 300
StatisticsModel.Chart.Attributes.Add("align", "left")
StatisticsModel.Chart.Titles.Add("Statistics for: " + StatisticsModel.ProductNumbers)
StatisticsModel.Chart.ChartAreas.Add(New ChartArea)
StatisticsModel.Chart.Series.Add(New Series)
StatisticsModel.Chart.Series(0).ChartType = SeriesChartType.Column
StatisticsModel.Chart.Series(0).Points.DataBindXY(StatisticsModel.FailedTPDescriptionList, "key", StatisticsModel.FailedTPDescriptionList, "value")
Now, I am trying to implement it in the View, but I have read many articles, and they suggest me to put the chart in a different controller. But that would mean I have to send the Chart object there, as I have many functions, that require a chart, and I thought the easiest way is to implement it in the Model, and then rendering it from there.
I tried using: http://code-inside.de/blog-in/2008/11/27/howto-use-the-new-aspnet-chart-controls-with-aspnet-mvc/
But the:
#Code
Dim writer As New HtmlTextWriter(Page.Response.Output)
End Code
Didn't work for me. I am using VB.NET
Can anyone help me? Suggestions are very welcome.
There are many, many ways of creating and showing charts in MVC, and the link you referred to is pretty good IMHO. I'm using c#, but the way I'm doing it is to use an img-tag in the view and point the src-attribute to a Controller action:
<img id="diagram" src="<%=Url.Action("DrawChartImage", "Home") %>" alt="Chart Diagram" />
The controller action returns a FileContentResult:
public ActionResult DrawChartImage()
{
using (var chartHelper = new ChartHelper())
{
//get data
var data = GetSomeDataForTheChart();
//draw chart
chartHelper.Draw(data);
//return chart as png image
return File(chartHelper.Image, "image/png");
}
}
The ChartHelper class implements IDisposable and has a helper property (Image) which returns the chart as a file, NOTE this is just sample/snippet code to show what I mean:
public class ChartHelper : IDisposable
{
private readonly Chart _chart;
public Chart Chart
{
get
{
return _chart;
}
}
public byte[] Image
{
get
{
using (var ms = new MemoryStream())
{
_chart.SaveImage(ms);
return ms.GetBuffer();
}
}
}
public ChartHelper()
{
_chart = new Chart();
_chart.Height = 300;
_chart.Width = 800;
_chart.ImageType = ChartImageType.Png;
_chart.Titles.Add("some title");
_chart.Legends.Add("some legend");
_chart.ChartAreas.Add("some chart area");
}
public void Draw(List<Data> data)
{
var dataArrays = GetDataArrays(data); //another helper method...
var series = new Series(tag);
series.Name = tag;
series.Legend = "tags";
series.ChartType = SeriesChartType.Spline;
series.BorderWidth = 4;
//sample way to add data below...
series.Points.DataBindXY(dataArrays.Item1, dataArrays.Item2);
_chart.Series.Add(series);
}
public void Dispose()
{
_chart.Dispose();
}
}
Works pretty well for me, hope it helps even if it's in C#.
EDIT If you want to create the image/chart in business logic called from your "main" Controller action, maybe you can do something like this where you generate the image/chart and then save it to disk, cache or database and pick it up from the image rendering controller action:
public ActionResult Index()
{
//this is call to your business logic or similar which generates the chart
byte[] image = GenerateImage();
//save image to cache, disk or from database
HttpContext.Cache["image"] = image;
return View();
}
public ActionResult Image()
{
//get image from cache, disk or from database
var image = HttpContext.Cache["image"] as byte[];
return File(image, "image/png");
}
//some sample/dummy code to generate image from a template
private byte[] GenerateImage()
{
using (var ms = new MemoryStream())
{
using (var image = System.Drawing.Image.FromFile(#"c:/temp/template.png"))
using (var brush = new SolidBrush(System.Drawing.Color.Black))
using (var bmp = new System.Drawing.Bitmap(image, image.Width, image.Height))
using (var g = System.Drawing.Graphics.FromImage(bmp))
{
g.DrawString(DateTime.Now.ToLongTimeString(), new Font("Consolas", 10), brush, 10, 10);
bmp.Save(ms, ImageFormat.Png);
}
return ms.ToArray();
}
}
And the view would be:
<img src="#Url.Action("Image")"/>