Can a void AjaxManager_AjaxRequest send JSON data back to the browser? - c#

Can AjaxManager_AjaxRequest only modify controls in its UpdatePanels or can it also send back JSON data in the response. Ideally just JSON data.
So in my ascx I have
protected void Page_Load(object sender, EventArgs e)
{
RadAjaxManager radAjaxManager = RadAjaxManager.GetCurrent(Page);
if (radAjaxManager != null)
{
radAjaxManager.AjaxRequest += AjaxManager_AjaxRequest;
}
}
private void AjaxManager_AjaxRequest(object sender, AjaxRequestEventArgs e)
{
// Somehow tweak it so response is just a JSON object.
}
I just inherited some legacy code and this is the fastest way for me to accomplish my aim without creating a web service to do this properly.
Is there anyway to do what I'm asking?

Yeah, this possible. Actually there are exists two available solutions. The first one is to send ajax request with jQuery ajax method (you can access jQuery functionality with $telerik.$). The only lack of this approach is that target server-side method must be static and you can't access page's ViewState as well as server control's properties values. The alternative approach is to use ScriptManager's RegisterDataItem method in AjaxManager_AjaxRequest method to pass JSON-serialized object back to client and get it in Sys.WebForms.PageRequestManager's endRequest event handler on client.
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
function endRequestHandler(sender, args) {
var dataItems = args.get_dataItems();
if (dataItems && dataItems["<%= RadAjaxManager1.UniqueID %>"]) {
alert(dataItems["<%= RadAjaxManager1.UniqueID %>"].Response);
}
}
</script>
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server" />
void AjaxManager_AjaxRequest(object sender, Telerik.Web.UI.AjaxRequestEventArgs e)
{
ScriptManager1.RegisterDataItem(radAjaxManager , new JavaScriptSerializer().Serialize(new { Response = "Hello, RadAjaxManager!" }), true);
}

Related

Trying to pass a value and recieve it on server side

i am trying to pass a value from client side and recieve it on server side on click of hyperlink.but it should not be called everytime on page load ,currently i am trying like this but it is reloaded every time when page load.so i want it to be called one time.
on click event of hyperlink TDC_No passing value to tdc.aspx
$.each(customers, function () {
var customer = $(this);
$("td", row).eq(0).find("a").text($(this).find("TDC_NO").text());
$("td", row).eq(0).find("a").attr("href", "TDC.aspx?Id=" + $(this).find("TDC_NO").text());
});
calling at page load side
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["Id"] != null)
{
TW12HVGI();
}
}
Any idea would be appreciated.
Not exactly sure what you're aiming for here. Do you mean that you pass the value - and the page loads but then subsequent actions on that page cause the TW12 function to execute again?
If so you are probably looking for a check on IsPostBack:
protected void Page_Load(object sender, EventArgs e){
if (!IsPostBack){
//if its not a post back - check for query string and run the TW12 function
if (Request.QueryString["Id"] != null)
TW12HVGI();
}
}
https://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback(v=vs.110).aspx
If you want to receive it on server side you will need to post back it using AJAX. On click of hyperlink send an ajax call and data to be saved along with it and then you will receive what ever you sent in action specified in ajax call.

ASP.NET: add postback to anchor

In my javascript file, I got an ajax to get all list and iterate these data and append <a id='userID' class='btn'>Assign ID<> to my list.
So, how do a add postback to these anchor and redirect it inside my method in the server. Below is my code but didn't work. When I click the achor button, it just redirect/refresh to the same page without doing any changes and didn't show the text.
<a id='uniqueID' class='btn assignID' href='javascript:void(0);' onclick='javascript:__doPostBack('uniqueID','')'>Assign ID</a>
protected void Action_assignID(object sender, EventArgs e)
{
// assign ID action
Response.Write("Pass");
}
You should be changed your button to:
<a id='uniqueID' class='btn assignID' href='javascript:void(0);' onclick="javascript:__doPostBack('uniqueID','Assign ID')">Assign ID</a>
And it's a good idea to implement the IPostBackEventHandler interface in your codebehind as below:
public partial class WebForm : Page, IPostBackEventHandler
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
}
}
public void RaisePostBackEvent(string eventArgument)
{
// do somethings at here
}
}
Hope this help!
The __doPostBack method really doesn't do anything special except, well... perform a POST operation back to the same page with two specific form arguments.
The first parameter is the __EVENTTARGET and the second parameter is the __EVENTARGUMENT.
The magic all happens in ASP.Net where it automagically wires up your controls to event handlers, but since you are creating these entirely in JavaScript the server doesn't know that those controls exist.
However, you can manually grab these values and do something with them.
//Client Side JavaScript:
__doPostBack('my-event', '42');
//Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
var target = Request.Params["__EVENTTARGET"];
var args = Request.Params["__EVENTARGUMENT"];
Target.Text = target; // 'my-event'
Argument.Text = args; // '42'
}
}

asp.net server side buttons clicks programatically

i have 2 server side asp.net buttons , i need to automate the buttons clicks.
i.e. After page_load, i need to click button1 and after its results are shown on the page, wait for 10 seconds and click button2 .
i tried the following sample code
protected void Page_Load(object sender, EventArgs e)
{
Button1_Click(Button1, null);
Thread.Sleep(10000);
Button2_Click(Button2, null);
}
protected void Button1_Click(object sender, EventArgs e)
{
changeLabel.Text = "Button1";
}
protected void Button2_Click(object sender, EventArgs e)
{
changeLabel.Text = "Button2";
}
}
i had 2 obeservations (maybe useful):
always Button2_Click(Button2, null); event is the latest when the page is fully loaded (which is obvious).
Page_Load(object sender, EventArgs e) doesnot
hit atall when programatically clicked the button.
Any idea how to achieve the solution.
What you are doing in your example is to call the handlers of button1 and button2's click events, that is not the same as having the user click the buttons, and for the form to postback to the server.
If you want the buttons to click them selves and having the post back to the server you need to add javascript that clicks the buttons for you.
If you want a javascript which hits a button for you after X seconds, i would do something like this:
in your aspx page:
<asp:button ID="Button1" runat="server" ClientIDMode="Static" OnClick="Button1_Click">
</asp:button>
in your javascript files or some block on your page:
<script type="text/javascript">
setTimeout(function(){
document.getElementById("Button1").click();
}, 10*1000); // 10 seconds
</script>
Important to note here is that you have to either set ClientIDMode="Static" on your button, otherwise it might have a very obscure name if you are using master pages, or you can do:
<script type="text/javascript">
setTimeout(function(){
document.getElementById("<%= Button1.ClientID %>").click();
}, 10*1000); // 10 seconds
</script>
if you have the javascript in your .aspx file rather then its own .js file.
ps: if you do Thread.Sleep(X) in an aspx page, you will only make the users browser wait for the X milliseconds more for the page to load, code run before the sleep will not be submitet to the clients browser in the way i think you want it to do.
Button_Click is server event, when invoked from client, browser post the relavent data to server and request of new page content, at that time Page_load is invoked.
if you want to do some thing, encapsulate action to some method and call that method in pre-render. Or other wise, use JavaScript.
protected void Page_PreRender(object sender, EventArgs e)
{
UpdateButton1()
Thread.Sleep(10000); // no need to put sleep
UpdateButton2();
}
protected void Button1_Click(object sender, EventArgs e)
{
UpdateButton1();
}
protected void UpdateButton1()
{
changeLabel.Text = "Button1";
}

How to call onclientclick after onclick

I've got this button
<asp:Button runat="server" ID="btnReviewDocs" CssClass="btnReviewDocs" data-theme="b"
Text="Review Documents" OnClick="btnReviewDocs_Click" OnClientClick="clickHyperlink();"/>
And in 'OnClick' event I'm assembling an URL that I need to set to asp:Hyperlink and at the end of the 'OnClick' I'm setting this URL to the 'NavigateURL' propery of the 'asp:Hyperlink'. Once the 'asp:Hyperlink' has the correct URL I need to call the 'clickHyperlink()' function.
function clickHyperlink() {
var href = $('#hlnkID').attr('href');
if (typeof href !== "undefined") {
$.mobile.showPageLoadingMsg();
window.location.href = href;
}
}
But the 'OnClientClick' event is executed always before the 'OnClick'. Any suggestions for a workaround?
I'm doing all this stuff, because I've got problems with JQuery Mobile and 'Response.Redirect(url);' is changing the page, but not the URL.
I believe that you don't really need to involve the Hyperlink control in the JS part.
Modify your JS function and remove the OnClientClick attribute from the btnReviewDocs button:
<script type="text/javascript">
function clickHyperlink(href) {
$.mobile.showPageLoadingMsg();
window.location.href = href;
}
</script>
On the server, in the btnReviewDocs_Click method:
protected void btnReviewDocs_Click(object sender, EventArgs e)
{
// TODO: set the url, maybe append some params to the
// hlnkID.NavigateUrl value
var url = "http://stackoverflow.com/";
ClientScript.RegisterStartupScript(Page.GetType(),
"clickHyperlink",
"clickHyperlink('" + url + "');",
true);
}
Use the RegisterStartupScript in the ClientScript object to run the code after postback--->
protected void btn_Click(object sender, EventArgs e)
{
//some code
this.ClientScript.RegisterStartupScript(this.GetType(), "clintClick", "clickHyperlink", true);
}
try this
protected void btnReviewDocs_Click(object sender, EventArgs e)
{
//something doing here
Page.ClientScript.RegisterStartupScript(this.GetType(), "test", "<script type='text/javascript'>clickHyperlink()</script>");//call javascript function
}
The answer is mentioned by #Alex Filipovici.
But first you should ask yourself do you really need to go back to the client side to do a redirect ?
Why not call :
Response.Redirect("MyURL");

Do a database query on Textbox onblur event

I am using asp.net 3.5 with C#. I need to do a database lookup when a user enters ProductID in txtProductID. I guess doing javascript is out of the question since this will have to be server side call.
I wrote this code in the page_load event of the webpage:
protected void Page_Load(object sender, EventArgs e)
{
txtProductID.Attributes.Add("onblur", "LookupProduct()");
}
protected void LookupProduct()
{
//Lookup Product information on onBlur event;
}
I get an error message: Microsoft JScript runtime error: Object expected
How can I resolve this ?
onblur is a client-side event. LookupProduct is a server-side method. You can't reference one from the other - there's simply no association whatsoever between the two.
There's no quick fix for this - you have to either trigger a postback on the client event (using ClientScriptManager.GetPostBackEventReference) or implement an Ajax callback using a library like Microsoft ASP.NET Ajax.
Alternatively, if you don't really need to fire this event on every blur, and only when the text has changed, then you can simply use the server-side TextBox.OnChanged event and set the TextBox's AutoPostBack property to true. Make sure you remember to set AutoPostBack, otherwise this won't get you anywhere.
Use the TextBox.TextChanged event.
ASPX markup:
<asp:TextBox ID="txtProductID" runat="server" AutoPostBack="true" OnTextChanged="txtProductID_TextChanged" />
Codebehind:
protected void txtProductID_TextChanged(object sender, EventArgs e)
{
// do your database query here
}
This should do the trick, as referenced here: http://www.codedigest.com/CodeDigest/80-Calling-a-Serverside-Method-from-JavaScript-in-ASP-Net-AJAX---PageMethods.aspx
These are the controls
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True" />
<asp:TextBox ID="txtTest" onblur="LookupProduct()" runat="server" />
This is the Javascript
<script language="javascript">
function LookupProduct()
{
PageMethods.LookupProduct('',OnSuccess, OnFailure);
}
function OnSuccess(result) {
if (result)
{
}
}
function OnFailure(error) {
}
</script>
This is the server sidewebmethod
[WebMethod]
public static bool LookupProduct()
{
return true;
}

Categories

Resources