I have a Table object that I have created and populated in my code behind. It had to be done this way for various reasons.
I call a WebMethod via AJAX from the client side to send a variable from a dropdown list and then the table gets populated in a static method in the code behind. I need to get the Table into an ASP.Net PlaceHolder. I cannot call a PlaceHolder from a static method.
Instead of using an ASP.NET AJAX Page Method to return the data from your client-side AJAX call, try using an ASP.NET HTTP Handler, because it will allow you to better control the content coming back via HTTP headers instead of having to encode the result of the ASP.NET AJAX Page Method call, like this:
public class GetHtmlHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
// Grab the drop down list variable value from the query string
// Use controls to build table or do it via StringWriter
// Create a table row with three cells in it
TableRow theTableRow = new TableRow();
for (int theCellNumber = 0; theCellNumber < 3; theCellNumber++)
{
TableCell theTableCell = new TableCell();
tempCell.Text = String.Format("({0})", theCellNumber);
theTableRow.Cells.Add(theTableCell);
}
// Create writers to render contents of controls into
StringWriter theStringWriter = new StringWriter();
HtmlTextWriter theHtmlTextWriter = new HtmlTextWriter(theStringWriter);
// Render the table row control into the writer
theTableRow.RenderControl(theHtmlTextWriter);
// Return the string via the StringWriter
context.Response.Write(theStringWriter.ToString());
}
public bool IsReusable
{
get
{
return false;
}
}
}
Now on the client-side, use the jQuery .ajax() function to call the HTTP Handler, like this:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "PATH_TO_HANDLERS/GetHtmlHandler.ashx?id=YOUR_DROP_DOWN_VALUE",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
// Select the placeholder control by class here and put HTML into it
$('.ThePlaceHolder').html(result);
}
});
});
Note: The above selector requires that you add a CssClass attribute to your PlaceHolder control, like this:
<asp:PlaceHolder id="PlaceHolder1" runat="server" CssClass="ThePlaceHolder" />
UPDATE:
Instead of using the class name in your jQuery selector, you can use the ID of the PlaceHolder, I had originally advised against this, because it is subject to name mangling when using master pages in ASP.NET. At any rate, there is the ClientIDMode attribute which you can use, like this:
<asp:PlaceHolder id="PlaceHolder1" runat="server" ClientIDMode="Static" />
Now your jQuery selector would look like this:
// Select the placeholder control by ID here and put HTML into it
$('#<%= PlaceHolder1.ClientID %>').html(result);
Note: I prefer to avoid the angle bracket (<%= %>) notation where possible.
Related
I have a C# Web Forms application that is displaying a jqGrid on the home page. I struggled with the jqGrid for a while as it was returning the "jqGrid is not a function" error on any page that inherited from site.master.
To solve this, I put the code and script references for the grid in a user control and then referenced the control on the home page:
<%# Register TagPrefix="My" TagName="GridControl" Src="~/UserControls/Grid.ascx"%>
<My:GridControl ID ="gridControl" runat="server" />
Inside Grid.ascx I have the code to populate the grid which gets it's data from a stored procedure inside a handler:
<script type="text/javascript">
$(function () {
$("#dataGrid").jqGrid({
url: 'Handler1.ashx',
datatype: 'json',
I used the handler along with Newtonsoft JSON.NET to avoid the json string length error.
The stored procedure has 11 parameters which when set to NULL, return all rows, which is what I want for the initial page load.
sqlCmd.Parameters.Add("#ProjNum", SqlDbType.Int).Value = DBNull.Value;
So now, I want to filter the results based on values from dropdowns on Default.aspx. The dropdowns are populated from SQL calls as well. But my question is how to get the values from the dropdowns into my handler?
I know I can do something like url: Handler1.ashx?asgnID=19 where I've just hardcoded the value, and then get it from the context.Request.QueryString, but I still don't know how to pass the value.
I've also read about using session, and I've tried passing a json string in ajax from default.aspx in a java button click event - which didn't work because the handler ends up getting called twice. I'm a little green on this stuff, and was hoping for a better alternative.
In case anyone is having the same issue, I did the following to solve it:
Create a function to extract the parameter from the url.
function GetParameterValues(param) {
var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < url.length; i++) {
var urlparam = url[i].split('=');
if (urlparam[0] == param) {
return urlparam[1];
}
}
}
Assign the parameter value to a variable and use it in your Jqgrid url:
$(function () {
var id = GetParameterValues('id');
$('#statusGrid').jqGrid({
url: 'Handler2.ashx?id=' + id.toString(),
datatype: 'json',
mtype: 'POST',
colNames: ['Status', 'Status Date', 'Status Time',...
And, inside the handler, extract the id from the context in ProcessRequest()
int ProjNum = Convert.ToInt32(context.Request["Id"]);
I have a Javascript Gage that displays a percent and refreshed every 5 seconds in an ASPX page. As of now I am refreshing the whole page. How can I refresh just the Javascript Gage? Refreshing the whole page is not good practice. The Gage is inside div gg11. I am new at javascript, how can I achieved this?
ASPX
<div id="gg11" class="gauge"></div>
<meta http-equiv="refresh" content="5; URL=http://localhost:63738/main.aspx">
ASPX.cs
protected void Page_Load(object sender, EventArgs e)
{
JavaScriptMethod();
}
protected void JavaScriptMethod()
{
Calculations();
StringBuilder sb = new StringBuilder();
sb.Append("<script>");
sb.Append("var gg1 = new JustGage({");
sb.Append("id: \"gg11\",");
sb.Append("donut: 0,");
sb.Append("title: \"LAKE WALES\",");
sb.Append("titleFontColor: \"#000000\",");
sb.AppendFormat("value: {0},", percent);
sb.Append("min: 0,");
sb.Append("max: 100,");
sb.Append("labelFontColor: \"#000000\",");
sb.Append("humanFriendlyDecimal: 1,");
sb.Append("decimals: 1,");
sb.Append("symbol: \"%\",");
sb.Append("startAnimationType : \"bounce\",");
sb.Append("refreshAnimationType: \"bounce\",");
sb.Append("startAnimationTime: 1000,");
sb.Append("gaugeWidthScale: 1.2,");
sb.Append("customSectors: [{color: \"#ff0000\",lo: 0,hi: 79}, {color: \"#ffa500\",lo: 80,hi: 89}, {color: \"#1eae1e\",lo: 90,hi: 100}],");
sb.Append("counter: true");
sb.Append("});");
sb.Append("</script>");
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "temp", sb.ToString(), false);
}
Use a combination of JavaScript, jQuery and ASP.NET AJAX Page Methods, like this:
Markup:
<div id="gg11" class="gauge"></div>
JavaScript:
$(document).ready(function() {
setInterval(doAjax, 5000);
});
function doAjax() {
$.ajax({
type: "POST",
url: "YourPageName.aspx/GetGage",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
if (result.hasOwnProperty("d")) {
// The .d is part of the result so reference it
// to get to the actual JSON data of interest
// Put result into DIV
$('#gg11').html(result.d);
}
else {
// No .d; so just use result
// Put result into DIV
$('#gg11').html(result);
}
}
});
}
Note: You will need to change the name of YourPageName.aspx to the name of your .aspx page. Also, the .d syntax was an anti-XSS protection put in by Microsoft in the ASP.NET 3.5 release of ASP.NET AJAX; therefore the check to see if the .d property is there or not.
Code-behind:
[WebMethod]
public static string GetGage()
{
Calculations();
StringBuilder sb = new StringBuilder();
sb.Append("<script>");
sb.Append("var gg1 = new JustGage({");
sb.Append("id: \"gg11\",");
sb.Append("donut: 0,");
sb.Append("title: \"LAKE WALES\",");
sb.Append("titleFontColor: \"#000000\",");
sb.AppendFormat("value: {0},", percent);
sb.Append("min: 0,");
sb.Append("max: 100,");
sb.Append("labelFontColor: \"#000000\",");
sb.Append("humanFriendlyDecimal: 1,");
sb.Append("decimals: 1,");
sb.Append("symbol: \"%\",");
sb.Append("startAnimationType : \"bounce\",");
sb.Append("refreshAnimationType: \"bounce\",");
sb.Append("startAnimationTime: 1000,");
sb.Append("gaugeWidthScale: 1.2,");
sb.Append("customSectors: [{color: \"#ff0000\",lo: 0,hi: 79}, {color: \"#ffa500\",lo: 80,hi: 89}, {color: \"#1eae1e\",lo: 90,hi: 100}],");
sb.Append("counter: true");
sb.Append("});");
sb.Append("</script>");
return sb.ToString();
}
Use the javascript setInterval method to make an ajax call to your server where your sever page returns the HTML markup for the specific part you are interested in. Remove the meta tag which refreshes the whole page.
Assuming you have jQuery loaded in your page
$(function(){
var intId= setInterval(function(){
$("#gg11").load("getgauge.aspx");}, 5000);
});
This will keep sending an ajax request to the server page every 5 seconds!
You should have the getgauge.aspx returns the HTML markup you want to show in the UI.
If you are interested in only the changed value (whenever some value is changed in server), You may look into libraries like SignalR which makes realtime communication an easy task.
this is my scenario: I have an asp website that can merge tiff file. So, to do this i need to use a c# function and it is called after a javascript event.
The c# is like this:
public void mergeImages(string initialUrl, string lastImageUrl)
{....}
I created two hidden field like this:
<input type="hidden" id="hi1" value="D:\\ProvaUpload\\1.tif" />
to get the value to pass at the function, because I didn't know in which way I can pass js variable to it.
I call the function in this way:
'<%mergeImages(par1,par2); %>';
In which way can I pass variable value to the function?
Decorate the method with WebMethod Attribulte:
[WebMethod]
public void mergeImages(string initialUrl, string lastImageUrl)
{....}
Get the hidden fields, and pass these to Jquery Ajax call, from a button click
var hdn1 = $('#hi1').val();
var hdn2 = $('#hi2').val();
var parameters = '{initialUrl:' + hdn1 + ', lastImageUrl:' + hdn2 + '}';
$.ajax({
type: "POST",
url: "page.aspx/mergeImages",
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
}
});
Refer the stackoverflow thread.
ASP.NET - Passing JSON from jQuery to ASHX
This will help you to understand to use handler file (ashx) to do ajax json request.
your requirement can be achieved with this concept.
you do not need to call cs method into javascript. you should post using ajax on any kind of handler file e.g ashx, asmx, or any other service .
Nothing to do much you just need to take an extra button which will be hide in output:
<asp:button id="btnGetAndPassvalues" runat="server" Text="hide" Onclick="btnGetAndPassvalues_Click" Style="display:none"/>
Now javascript function should be like below:
<script>
$('[id$=btnUpload]').live('click', function (e) {
// code to finish Upload prosess
$('[id$=btnGetAndPassvalues]').click();
});
</script>
That's all and in click event get the values of hidden field:
protected void btnGetAndPassvalues(Object sender,EventArgs e){
string hd1=hiden1.Value;
string hd2=hiden2.Value;
}
or you can make AJAX Call,
one of the easy way to achieve this :-
As you already have two hidden fields but must add runat attribute to it ,so that
you can get their values at server side. Let's Say:-
<input type="hidden" id="hi1" value="D:\\ProvaUpload\\1.tif" runat="server" />
<input type="hidden" id="hi2" value="D:\\ProvaUpload\\2.tif" runat="server" />
and Make a hidden button :-
<asp:button id="btnhidden" runat="server" Text="hide" Onclick="btnhidden_Click" Style="display:none"/>
Now you can click the button in javascript function :-
function UploadFinished()
{
//your JS code:-
// After finish uploading ..Click the button .. i have used jquery for simplicity:-
$('input[id$="btnhidden"]').click();
}
Now in your code behind :-
protected void btnhidden_Click(Object sender,EventArgs e)
{
// you can get hidden fields values here ....
string val1=hi1.Value;
string val2=hi2.Value;
// Call your merge function here :-
mergeImages(val1,val2);
}
In ASP.NET MVC 4 how can I render HTML on load. I am saving some html string encoded in this form in my sql server database as type nvarchar(max).
<li><li><img id="fbPic" src="http://graph.facebook.com/567818188/picture" style="display: inline; padding-right: 10px;"><b>Bernice Zerafa</b></li><pre class="word-wrap" style="margin-left: 10%;">hellooo</pre></li>
*EDIT:*Please note that the above string is being html unencoded correctly therefore it actually shows like this:
<li><li><img id="fbPic" src="http://graph.facebook.com/567818188/picture" style="display: inline; padding-right: 10px;"><b>Bernice Zerafa</b></li><pre class="word-wrap" style="margin-left: 10%;">helloooo </pre></li>
Now on load of the page I will have a list of those html strings which are all list items with various childnodes to be appended to a unordered list tag. The list is returning ok. But it's only being displayed as is on the page i.e. the actual string is showing and the html is not being rendered.
This is my Controller Action:
public ActionResult LoadPosts(int groupId)
{
var postedText = new List<string>();
IEnumerable<Post> posts;
using (CodeShareEntities conn = new CodeShareEntities())
{
posts = conn.Posts.Where(g => g.GroupId == groupId);
foreach (var post in posts)
{
postedText.Add(post.PostData);
}
}
return Json(new { PostedText = postedText });
}
This is my jQuery Ajax call on load of the page. #posts is an empty <ul> in my html
jQuery.ajax({
type: 'POST',
url: '/Groups/LoadPosts',
data: { groupId: grpid },
success: function (postData) {
$.each(postData, function (index, postText) {
**postText = htmlUnencode(postText);**
$("#posts")[0].innerHTML = postText;
//// what can I do here instead of innerHTML to be
//// able to view the html correctly ?
//// append() and insert() methods in JQuery have the same result
//// I found something called #Html.Raw(Json.Encode()) maybe
//// this is relevant here ? How can I use this correctly ?
});
$('#posts').css('background', 'white');
},
traditional: true
});
Any help would be greatly appreciated!
It seems like your html is double encoded. Try this
$.each(postData, function (index, postText) {
**postText = htmlUnencode(postText);**
$("#posts").append($($("<div/>").html($("<div/>").html(test).text()).text()));
});
Here is a Fiddle sample.
just by looking at your
<li><li><img id="fbPic" src="http://graph.facebook.com/567818188/picture" style="display: inline; padding-right: 10px;"><b>Bernice Zerafa</b></li><pre class="word-wrap" style="margin-left: 10%;">hellooo</pre></li>
i doubt it going to render correctly it not seems like a valid html and you constantly appending so you might use something like
$("#posts").append(postText);
I would like to fill a DataTable with the Page_Load event, then be able to access it from the ashx handler page when an Ajax call is sent from the client side. Currently, the DataTable is filled every time I make an Ajax call to the handler page, which makes it a bit on the slow side. Here's what I currently do:
Default.aspx.cs
public DataTable fillSCOMDTts()
{
//SCOM TableAdapter and DataTable
dsCIInfoTableAdapters.vManagedEntityTableAdapter taSCOM;
taSCOM = new dsCIInfoTableAdapters.vManagedEntityTableAdapter();
dsCIInfo.vManagedEntityDataTable dtSCOM = new dsCIInfo.vManagedEntityDataTable();
taSCOM.Fill(dtSCOM);
return dtSCOM;
}
Ajax call from client-side:
$.ajax({
url: '/FindFootprint.ashx?queryStr=' + strParameter,
dataType: 'json',
success: function (data) {
//do stuff
});
FindFootprint.ashx.cs
public void ProcessRequest(HttpContext context)
{
string strParameter = context.Request.QueryString["queryStr"];
bool binSCOMts = false;
Default d = new Default();
DataTable dtSCOMts = d.fillSCOMDTts();
var qstSCOMts = (from row in dtSCOMts.AsEnumerable()
let fieldName = row.Field<string>("DisplayName")
where fieldName.ToLower().Contains(strParameter)
select fieldName).ToArray();
if (qstSCOMts.Length > 0)
{
binSCOMts = true;
}
JsonObject JO = new JsonObject();
JO.Add("assetName", strParameter);
JO.Add("inSCOMts", binSCOMts.ToString());
context.Response.ContentType = "text/plain";
context.Response.Write(JO.ToString());
}
A handler is not really supposed to know anything about code/objects outside of itself.
If you're able to not use the handler in this case then you could set a private static DataTable MyTable; in your page.
Then on your page_load populate this static property.
You should then be able to access this property inside a web method that you call from you Ajax. The web method would be part of your pages code-behind so will have access to the private property set above. Put the code from your handler into this web method - bar the binding.