export to excel from ajax request asp.net MVC kendo UI - asp.net

I am working on a asp.net MVC with kendo UI.
I want a custom button to install the data from a specific date into Excel.
I cannot use the ".Excel" in the grid because I need to filter the data before I install them.
I tried to connect to a method with ajax request:
toolbar.Template(
#<div>
<label>#WebResources.LogFilterText</label>
#(Html.Kendo().DatePicker()
.Name("datepicker")
.Value(DateTime.Today)
.Format("dd.MM.yyyy")
)
#(Html.Kendo().Button()
.Name("excelButton")
.Events(e => e.Click("getExcel"))
.Content("To Excel")
)
</div>
)
this is the javscript function:
function getExcel() {
var url = '/LogAdmin/GetExcel/';
$.ajax({
url: url,
data: { id: kendo.toString($("#datepicker").data("kendoDatePicker").value(), "dd.MM.yyyy") }, //parameters go here in object literal form
type: 'GET',
datatype: 'json',
success: function (data) {
alert("da");
$("#test").html(data);
},
error: function () { alert("Error has been accured."); }
});
}
and here is the controller method:
public ActionResult GetExcel([Bind(Prefix = "id")] string date)
{
// result is a valid list from Linq.
GridView gridview = new GridView();
gridview.DataSource = result;
gridview.DataBind();
// Clear all the content from the current response
Response.ClearContent();
Response.Buffer = true;
// set the header
Response.AddHeader("content-disposition", "attachment; filename = itfunda.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
// create HtmlTextWriter object with StringWriter
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// render the GridView to the HtmlTextWriter
gridview.RenderControl(htw);
// Output the GridView content saved into StringWriter
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
return View();
}
I do not get an error, and I receive an html table. if I show it on a div then it looks a like a correct table.
but how to save it to excel? anybody can help me?

Related

Google chart is not loading in asp.net using JSON

I am trying to visualize data using google charts.But the chart is not displaying.I want to display data which is retrieved from sqlserver database
here is my code.
<div id="chart_div" style="width:500px;height:400px">
<%-- Here Chart Will Load --%>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var jdata = $.ajax({
url: "GetData.aspx",
dataType: "json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jData);
var options = {
title: 'Chess opening moves',
width: 900,
legend: { position: 'none' },
chart: {
title: 'Chess opening moves',
subtitle: 'popularity by percentage'
},
bars: 'horizontal', // Required for Material Bar Charts.
axes: {
x: {
0: { side: 'top', label: 'amount' } // Top x-axis.
}
},
bar: { groupWidth: "90%" }
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, options);
};
</script>
</div>
GetData.aspx
public partial class GetData : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
JavaScriptSerializer js = new JavaScriptSerializer();
string arr = JsonConvert.SerializeObject(get(), Formatting.None,
new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
Response.Write(arr);
}
private object get()
{
List<object> ls = new List<object>();
SqlConnection con = new SqlConnection("Data Source=dell-pc;Initial Catalog=hospital;Integrated Security=True");
SqlCommand cmd = new SqlCommand("select top(5) p_id, amount from payments", con);
con.Open();
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
ls.Add(dr);
}
return ls;
}
}
The JsonArray loads as follows.
[{"RowError":"","RowState":2,"Table":[{"p_id":"PT1","amount":7000.0000},{"p_id":"PT2","amount":35000.0000},{"p_id":"PT8","amount":95000.0000},{"p_id":"PT10","amount":51000.0000},{"p_id":"PT3","amount":1200.0000}],"ItemArray":["PT1",7000.0000],"HasErrors":false},{"RowError":"","RowState":2,"Table":[{"p_id":"PT1","amount":7000.0000},{"p_id":"PT2","amount":35000.0000},{"p_id":"PT8","amount":95000.0000},{"p_id":"PT10","amount":51000.0000},{"p_id":"PT3","amount":1200.0000}],"ItemArray":["PT2",35000.0000],"HasErrors":false},{"RowError":"","RowState":2,"Table":[{"p_id":"PT1","amount":7000.0000},{"p_id":"PT2","amount":35000.0000},{"p_id":"PT8","amount":95000.0000},{"p_id":"PT10","amount":51000.0000},{"p_id":"PT3","amount":1200.0000}],"ItemArray":["PT8",95000.0000],"HasErrors":false},{"RowError":"","RowState":2,"Table":[{"p_id":"PT1","amount":7000.0000},{"p_id":"PT2","amount":35000.0000},{"p_id":"PT8","amount":95000.0000},{"p_id":"PT10","amount":51000.0000},{"p_id":"PT3","amount":1200.0000}],"ItemArray":["PT10",51000.0000],"HasErrors":false},{"RowError":"","RowState":2,"Table":[{"p_id":"PT1","amount":7000.0000},{"p_id":"PT2","amount":35000.0000},{"p_id":"PT8","amount":95000.0000},{"p_id":"PT10","amount":51000.0000},{"p_id":"PT3","amount":1200.0000}],"ItemArray":["PT3",1200.0000],"HasErrors":false}]
I think there is something wrong when json is loading. please help
The main reason here that you fail to load json data is probably because you use a full aspx page GetData.aspx (and there you send wrong header, content type)
Change that to a handler, make a new handler not just rename the page, something like getdata.ashx and place there your code.
Be sure to send the correct content type context.Response.ContentType, and check that you send only the correct json data
the answers here can help : ASP.NET Returning JSON with ASHX

Binding Lable from webmethod using ajax

Hi guyes i am trying to read data from webmethod and pass the value to my lable in aspx page. for this i take a use of Ajax and webmethod. my problem is when i am not able to bind data on success to my lable controle.
my .asmx page.
public static string str;
[WebMethod]
public string GetEmployeeDetail(string name)
{
str = name;
Get(str);
string daresult;
daresult = Get(str);
return daresult;
}
[WebMethod]
public string Get(string str)
{
List<string> rst = new List<string>();
using (SqlConnection con = new SqlConnection("..."))
{
using (SqlCommand cmd = new SqlCommand("select practice_short_name from PRACTICE_DETAIL where Practice_Name = '" + str + "'",con))
{
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
rst.Add(string.Format("{0}", dr["practice_short_name"]));
}
System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return jSearializer.Serialize(rst);
}
}
}
and here is my ajax call function in aspx page.
function fun() {
var ddlpsn = document.getElementById("<%=ddlPSN.ClientID%>");
$(ddlpsn).change(function () {
var s = $(this).val();
$.ajax({
type: 'POST',
url: 'AutoCompleteService.asmx/GetEmployeeDetail',
data: '{name: "' + s + '" }',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
//i think i need to do some changes in here but not getting what to do.
$('#lblpriority').text(data.val);
},
error: function (error) {
console.log(error);
}
});
});
};
You need to change data.val to data.d. Data returned from WebMethod is contained in d property if you have not explicitly defined your own property for returned data.
$('#lblpriority').text(data.d);
You need to make your WebMethod static in order to called by ajax.

Getting [object Object] error when call JQuery Ajax function for Json data

I'm getting the following error when try to read json data from asp.net function, here is the image error
Here is the jQuery code,
<script type="text/javascript">
$(document).ready(function () {
$("#getdata").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetData",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.d);
// $("#company").html(data.d);
console.log(data);
},
error: function (error) {
alert(error);
}
});
});
});
</script>
what wrong I did to get this error. Appreciate your any help.
getting this error from console log,console.log(error)
The reason you are seeing that is that data.d is an object representing the returned JSON text response. When you pass in an object into alert, it displays [object Object]. Whatever you are looking for will be a property of data.d. I would put a breakpoint on that line and see what properties are available. It'll be something like data.d.myProperty which will contain the actual string / HTML you are trying to work with.
dont use alert! That will show this only.
Since your response is a Json Object, please try to JSON.stringify it or use console.log to view the data
Finally, I found what was the issue, I have to add "[WebMethod()]" declaration just before the asp.net function. For example,
[WebMethod()]
public static string GetData()
{
try
{
string strjson;
string connectionstring = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
SqlConnection Con = new SqlConnection(connectionstring);
DataSet DS = new DataSet();
String CmdText = "Select Compname,compadd1,compadd2,compemail from aas_company where compid=#cmpid";
SqlCommand cmd = new SqlCommand(CmdText, Con);
cmd.Parameters.Add("#cmpid", SqlDbType.Int).Value = 22;
Con.Open();
SqlDataAdapter DA = new SqlDataAdapter(cmd);
DA.Fill(DS);
DataTable dTable = DS.Tables[0];
strjson = GetJSONString(dTable);
Con.Close();
return strjson;
}
catch (Exception ex)
{
throw new System.Exception("Error In Get Data" + ex.Message);
}
}
This answer not for experts only for just beginners, thank you.

Why am I having to set the dataType to text?

I have the following script which works, but I don't understand why it will not work when the type is set to json:
Serverside:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Response.Clear()
Response.ContentType = "text/plain" '//#### <- should't this be text/json? ###
Response.Write(getTabFrame())
Response.End()
End Sub
Function getTabFrame() As String
objStringBuilder = New StringBuilder()
objStringBuilder.Append("[")
objStringBuilder.Append("{""key"":1,""value"":""Default""},")
objStringBuilder.Append("{""key"":2,""value"":""Reports""},")
objStringBuilder.Append("{""key"":3,""value"":""Other""}")
objStringBuilder.Append("]")
Return objStringBuilder.ToString
End Function
Clientside:
$.ajax({
url: 'serverside',
type: 'GET',
dataType: 'text', //#### <------------------------ shouldn't this be json? ###
error: function(xhr, status, error) {
alert('Error: ' + status + '\nError Text: ' + error + '\nResponse Text: ' + xhr.responseText);
},
success: function(results) {
var obj = jQuery.parseJSON(results);
var len = obj.length;
for(i=0; i<len; i++) {
$("#tabs").tabs("add","tabs.aspx?tab=" + obj[i].key, obj[i].value)
};
}
});
When I change those values to json, the whole thing stops working and returns "null"...
Why?
if dataType is json, you don't need to do parseJSON on results - it will already be a javascript object literal.
Try using Response.ContentType = "application/json"; on server side, and in AJAX call use
contentType: "application/json; charset=utf-8",
dataType: "json",
I think it should be an appropriate to use
• Response.ContentType = "text/html";
The XML validates and checks the markup validity of Web documents in HTML, XHTML, SMIL, MathML, etc. to conform to w3 standards.
SAMPLE CODE: (With error)
protected void Page_Load(object sender, EventArgs e)
{
Response.Clear();
Response.ContentType = "text/json"; //#### <- should't this be ‘application/json’?
Response.Write(getTabFrame());
Response.End();
}
private string getTabFrame()
{
var objStringBuilder = new StringBuilder();
objStringBuilder.Append("[");
objStringBuilder.Append("{\"key\":1,\"value\":\"Default\"},");
objStringBuilder.Append("{\"key\":2,\"value\":\"Reports\"},") ;
objStringBuilder.Append("{\"key\":3,\"value\":\"Other\"}");
objStringBuilder.Append("]");
return objStringBuilder.ToString();
}
Page Error Output:
The XML page cannot be displayed
Cannot view XML input using style sheet. Please correct the error and then click the Refresh button, or try again later.
Invalid at the top level of the document. Error processing resource 'http://localhost:1713/Default.aspx'. Line 1, Position...
[{"key":1,"value":"Default"},{"key":2,"value":"Reports"},{"key":3,"value":"Other"}]
^
SAMPLE CODE: (No error)
protected void Page_Load(object sender, EventArgs e)
{
Response.Clear();
Response.ContentType = "text/html"; //#### <- should't this be text/html? ###
Response.Write(getTabFrame());
Response.End();
}
private string getTabFrame()
{
var objStringBuilder = new StringBuilder();
objStringBuilder.Append("[");
objStringBuilder.Append("{\"key\":1,\"value\":\"Default\"},");
objStringBuilder.Append("{\"key\":2,\"value\":\"Reports\"},") ;
objStringBuilder.Append("{\"key\":3,\"value\":\"Other\"}");
objStringBuilder.Append("]");
return objStringBuilder.ToString();
}
Page Output(No error):
[{"key":1,"value":"Default"},{"key":2,"value":"Reports"},{"key":3,"value":"Other"}]

how can we load usercontrol using generic handler?

i want to load a user control using jquery ajax. One possible i found is to load usercontrol through generic handler. Anyone help me plsss. here the ajax code i am using to call the control.
<script type="text/javascript">
function fillSigns() {
$.ajax({
url: "usercontrolhandler.ashx?control=signs.ascx",
context: document.body,
success: function (data) {
$('#signdiv').html(data);
}
});
}
</script>
and here is the code in handler file
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
Page page = new Page();
UserControl ctrl = (UserControl)page.LoadControl("~/" + context.Request["control"] + ".ascx");
page.Form.Controls.Add(ctrl);
StringWriter stringWriter = new StringWriter();
HtmlTextWriter tw = new HtmlTextWriter(stringWriter);
ctrl.RenderControl(tw);
context.Response.Write(stringWriter.ToString());
}
This code raises object reference not found error at below shown line.
page.Form.Controls.Add(ctrl);
It seems page.Form is null here, that's why you've got a null reference exception. You could add your user control to the page's control collection instead:
page.Controls.Add(ctrl);
You could also use HttpServerUtility.Execute method for page rendering:
StringWriter output = new StringWriter();
HttpContext.Current.Server.Execute(page, output, false);
And finally take a look onto Tip/Trick: Cool UI Templating Technique to use with ASP.NET AJAX for non-UpdatePanel scenarios article by Scott Guthrie which covers your problem.
Try this:
Page page = new Page {ViewStateMode = ViewStateMode.Disabled};
HtmlForm form = new HtmlForm { ViewStateMode = ViewStateMode.Disabled };
form.Controls.Add(ctrl);
page.Controls.Add(form);
then:
StringWriter stringWriter = new StringWriter();
HtmlTextWriter tw = new HtmlTextWriter(stringWriter);
page.RenderControl(tw);
context.Response.Write(stringWriter.ToString());

Resources