JavaScript in ASP.Net CodeBehind - javascript

I am having trouble with some javascript that I have added to the codebehind. The goal I am trying to achieve here is on the page load to do another postback. Now, you may find this odd, but there is method to my madness.
In my ASP.Net Wizard, I have a textbox that contains a date populated from another step. This date is then used to populate 3 other controls with financial information. It is necessary for these 3 other controls to be populated on the load of this step. Now I have tried to do simply on page_load, but this doesn't work as certain controls either don't exist or the date isn't in the textbox. I have also tried to do this on the page render method, but this didn't work either for the same reasons.
So, I have resorted to using javascript executing a double postback, but it is causing all sorts of problems.
Here is the code from the Page_Load :
Dim validateFinancial as String = "<script language='javascript'>window.onload = function() ( ValidateFinancialDate() { __doPostBack('<%= UpdatePanel2.ClientID %>'); return false; })</script>"
Page.ClientScript.RegisterStartUp(Me.GetType(), "MyScript", validateFinancial, false)
It is not firing and in the javascript error box you see in the bottom left hand corner of the browser it says missing ";". If I remove the javascript code and simply added it to the markup with the function name in the string it will work with errors, but this when posting to the webserver causes the AJAX controls to fail on the whole page.
Is there away of getting this to work, please?

Your problem is that
<%= UpdatePanel2.ClientID %>
will not be interpreted. at the time when you want your javascript to post back, ASP has already finished rendering your page. You're goin to have to find another way of passing your UpdatePanel2.ClientID value.

You shouldn't use <%= UpdatePanel2.ClientID %> on backend side. Get __doPostBack('<%= UpdatePanel2.ClientID %>') equivalent using ClientScript.GetPostBackEventReference(UpdatePanel2, string.Empty); replace your __doPostBack('<%= UpdatePanel2.ClientID %>') with return value of mentioned method.
More detailed:
Let's start from the beginning. You need postback to be initiated by UpdatePanel2 after page loaded on client.
The correct JS function pattern should be:
window.onload = function() { ValidateFinancialDate(); %Do postback%; return false;};
To obtain that %Do postback% function call for UpdatePanel2 we need to use ClientScript.GetPostBackEventReference(UpdatePanel2, string.Empty) backend method,
which will produce correct JS __doPostBack function call to make postback request initiated by UpdatePanel2 control.
So working example on C# will be as following:
string postbackReference = Page.ClientScript.GetPostBackEventReference(UpdatePanel2, string.Empty);
string validateFinancial = "window.onload = function() { ValidateFinancialDate(); " + postbackReference + "; return false;};";
Page.ClientScript.RegisterStartUp(this.GetType(), "MyScript", validateFinancial, true);
Please pay attention to true argument of RegisterStartUp method, this will wrap validateFinancial script contents into tags automatically.
But this workaround with double postback seems artificial for the problem you're trying to solve, if you provide more source code
we can find better solution.

Related

Need to convert Web Form JavaScript to a js file

Basically I have three functions embedded into my form. I want to move this into a js file that I have already. I did this previously and my pop ups are working but now I want to move one function which executes the onclick event for a download button and the other two functions belonging to my autocomplete extender so I can display the results how I want them.
I have been messing around but I cannot seem to get this working.
This is my JavaScript function in Web Forms
function Download() {
__doPostBack("<%= btnDownload.UniqueID %>", "OnClick");
}
This is what I have tried in a js file
function Download(button) {
__doPostBack(button, 'OnClick');
}
and this is how I am calling it
ClientScript.RegisterStartupScript(Me.GetType(), "download", "Download(" & btnDownload.ClientID & ");", True)
please can somebody give me a clue to what I am missing and before I forget yes, the file is in my headers
<script type="text/javascript" src="js/importBuyer.js"></script>
The javascript function __doPostBack("<%= btnDownload.UniqueID %>", "OnClick"); expect a string as the client ID of the button. So you need to construct the calling script with ID parameter as string as follows:
ClientScript.RegisterStartupScript(Me.GetType(), "download", "Download(""" & btnDownload.ClientID & """);", True)
Note the double double-quotes ("") above so that the rendered javascript will be like :
Download("btnDownloadID");
From the example you've posted it seems that the webform way was sending the UniqueID and you are sending the ClientID
So you probably only need to send the UniqueID property instead.
I am wondering why should you do that. I would expect you to move from webforms to an API base backend but I can't understand why you want to separate the js integration part while keeping the webforms backend - I would understand if you'd separated the js logic part... not the part that communicates with the webforms
Hoped that helped
Here is a link describing the difference

Is there a way to use javaScript syntax inside Html helper

I have the following code inside my razor view:-
#Html.PagedListPager(Model , page => Url.Action("Index","Server", new
{
searchTerm = ViewBag.searchTerm,
page,
sort = ViewBag.CurrentSortOrder,
pagesize = $("#pagesize").val()
}),
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(PagedListRenderOptions.ClassicPlusFirstAndLast,
new AjaxOptions
{
UpdateTargetId = "ServerTable" ,
LoadingElementId="progress2"
}))
But i am unable to get the value of field using the following $("#pagesize").val(), so can anyone adivce if i can use a javaScript like syntax inside an Html helper ?
Thanks
The answer is : NO WAY!
Because:
You cannot pass anything from javascript to razor without going through the server.
That is because the razor is executed server side (hence the c# in it). The controller is called, that class is instantiated, then the method is invoked which matches the action requested, and then a view is returned. When the view is returned, the c# code in the view is executed. Once all code has been executed, it issues the html page in the response and then the javascript runs on the client. For you to get from javascript to razor, you would have to issue a new request to go through that path from the beginning in order to come back out in the end.
Solve this issue server side.
More detailed information please see this link:
Pass js variable or inout value to razor

Passing javascript variable to partial via render_javascript

I receive a google ID from an Ajax call and then want to use that ID to update a button on my view.
Here is the code in new.js.erb, which is linked to a new.html.erb.
Problem is, I don't know how to pass the variable's content. Restaurant is a json. The alert returns the correct ID and when I search my db on the terminal with the returned google id I find the restaurant.
Here is the code:
alert(restaurant["google_id"]);
var google_id = restaurant["google_id"];
$("#rating_bar").html("<%= escape_javascript(render 'reviews/buttons/full_profile_rate_restaurant', :google_id => "+google_id+".html_safe) %>");
What happens is that the variable being passed is the string "google_id" instead of the combination of letters and numbers that is the google ID. I've tried multiple approaches, this is just one of many wrong one - I think this question is pretty easy for anyone who knows their JS really well.
It is not possible to pass a JS variable to the ruby partial.
As Ryan Bigg explained for the same type of problem here, its not possible to send the variable while rendering that partial. We need to work out some thing else. Even i also had the same issue once.
Alternatively,
if that is google_id is only a variable to display in the partial, then update those divs manually after rendering that partial.
like
$("#rating_bar").html("<%= escape_javascript(render 'reviews/buttons/full_profile_rate_restaurant', :google_id => "sample_id") %>");
// Now update the required elements
$("#what-ever-ids").text(google_id);
or just create some other action in that controller, and call send an ajax request to that action, and there you will have this js variable, and in that js.erb file render the same partial which you actually want to update with the google_id variable.

Error while trying to get asp.net(C#) textbox text from ajax static WebMethod

I am using an ajax htmleditor in asp.net web application so i am trying to get the text the user has entered in the editor then i will send that text back to the client javascript function that will show the text in a div. But I am getting this error "Object reference not set to an instance of an object."
Firstly i tried to access the text of textbox linked with htmleditorextender through javascript but it was not working for me so i moved to ajax webmethod but this time also i am facing a problem. Please Help me.
[System.Web.Services.WebMethod]
public static string seteditor()
{
String x="";
try
{
Content c = new Content();
x = c.txteditor.Text;
}
catch (Exception ex) { x=ex.Message; }
return x;
}
Here, txteditor is the ID of asp:textbox which is linked with ajaxcontroltoolkit htmleditorextender.
You cannot get your aspx controls inside a static method.
If you are Calling a static method from jquery means the Page and its Controls don't even exist. You need to look another workaround for your problem.
EDIT:
I always pass my control values to page methods like this:
Assume I have two text controls: txtGroupName and txtGroupLevel
...My JS with Jquery will be :
var grpName = $("#<%=txtGroupName.ClientID%>").val();
var grpLevel = $("#<%= txtGroupLevel.ClientID %>").val();
data: "{'groupName':'" + grpName + "','groupLevel':'" + grpLevel + "'}",
Where groupName and groupRights are my webmethod parameters.
EDIT2:
Include your script like this:
<script type="text/javascript" src="<%= ResolveUrl("~/Scripts/jquery-1.4.1.js") %>"></script>
I suggest you to use the latest jquery version.
Web methods do not interact with the page object or the control hierarchy like this. That's why they're static in the first place. You need to pass the text from the client as a parameter to the web method, not read it from the textbox.
This issue was torturing me from last 18 hours continuouslyFirst I tried javascript than webmethod and than on user1042031's suggestion I tried jquery and than again I tried javascript and look how much easily it can be done with a single line of code.
var a = document.getElementById('<%= txteditor.ClientID %>').value;
read this stackoverflow article Getting Textbox value in Javascript
I apologize to everyone who responded me in this question but i have not found that article in my initial search.

Call ASP.NET function from JavaScript?

I'm writing a web page in ASP.NET. I have some JavaScript code, and I have a submit button with a click event.
Is it possible to call a method I created in ASP with JavaScript's click event?
Well, if you don't want to do it using Ajax or any other way and just want a normal ASP.NET postback to happen, here is how you do it (without using any other libraries):
It is a little tricky though... :)
i. In your code file (assuming you are using C# and .NET 2.0 or later) add the following Interface to your Page class to make it look like
public partial class Default : System.Web.UI.Page, IPostBackEventHandler{}
ii. This should add (using Tab-Tab) this function to your code file:
public void RaisePostBackEvent(string eventArgument) { }
iii. In your onclick event in JavaScript, write the following code:
var pageId = '<%= Page.ClientID %>';
__doPostBack(pageId, argumentString);
This will call the 'RaisePostBackEvent' method in your code file with the 'eventArgument' as the 'argumentString' you passed from the JavaScript. Now, you can call any other event you like.
P.S: That is 'underscore-underscore-doPostBack' ... And, there should be no space in that sequence... Somehow the WMD does not allow me to write to underscores followed by a character!
The __doPostBack() method works well.
Another solution (very hackish) is to simply add an invisible ASP button in your markup and click it with a JavaScript method.
<div style="display: none;">
<asp:Button runat="server" ... OnClick="ButtonClickHandlerMethod" />
</div>
From your JavaScript, retrieve the reference to the button using its ClientID and then call the .click() method on it.
var button = document.getElementById(/* button client id */);
button.click();
The Microsoft AJAX library will accomplish this. You could also create your own solution that involves using AJAX to call your own aspx (as basically) script files to run .NET functions.
I suggest the Microsoft AJAX library. Once installed and referenced, you just add a line in your page load or init:
Ajax.Utility.RegisterTypeForAjax(GetType(YOURPAGECLASSNAME))
Then you can do things like:
<Ajax.AjaxMethod()> _
Public Function Get5() AS Integer
Return 5
End Function
Then, you can call it on your page as:
PageClassName.Get5(javascriptCallbackFunction);
The last parameter of your function call must be the javascript callback function that will be executed when the AJAX request is returned.
You can do it asynchronously using .NET Ajax PageMethods. See here or here.
I think blog post How to fetch & show SQL Server database data in ASP.NET page using Ajax (jQuery) will help you.
JavaScript Code
<script src="http://code.jquery.com/jquery-3.3.1.js" />
<script language="javascript" type="text/javascript">
function GetCompanies() {
$("#UpdatePanel").html("<div style='text-align:center; background-color:yellow; border:1px solid red; padding:3px; width:200px'>Please Wait...</div>");
$.ajax({
type: "POST",
url: "Default.aspx/GetCompanies",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: OnSuccess,
error: OnError
});
}
function OnSuccess(data) {
var TableContent = "<table border='0'>" +
"<tr>" +
"<td>Rank</td>" +
"<td>Company Name</td>" +
"<td>Revenue</td>" +
"<td>Industry</td>" +
"</tr>";
for (var i = 0; i < data.d.length; i++) {
TableContent += "<tr>" +
"<td>"+ data.d[i].Rank +"</td>" +
"<td>"+data.d[i].CompanyName+"</td>" +
"<td>"+data.d[i].Revenue+"</td>" +
"<td>"+data.d[i].Industry+"</td>" +
"</tr>";
}
TableContent += "</table>";
$("#UpdatePanel").html(TableContent);
}
function OnError(data) {
}
</script>
ASP.NET Server Side Function
[WebMethod]
[ScriptMethod(ResponseFormat= ResponseFormat.Json)]
public static List<TopCompany> GetCompanies()
{
System.Threading.Thread.Sleep(5000);
List<TopCompany> allCompany = new List<TopCompany>();
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
allCompany = dc.TopCompanies.ToList();
}
return allCompany;
}
Static, strongly-typed programming has always felt very natural to me, so at first I resisted learning JavaScript (not to mention HTML and CSS) when I had to build web-based front-ends for my applications. I would do anything to work around this like redirecting to a page just to perform and action on the OnLoad event, as long as I could code pure C#.
You will find however that if you are going to be working with websites, you must have an open mind and start thinking more web-oriented (that is, don't try to do client-side things on the server and vice-versa). I love ASP.NET webforms and still use it (as well as MVC), but I will say that by trying to make things simpler and hiding the separation of client and server it can confuse newcomers and actually end up making things more difficult at times.
My advice is to learn some basic JavaScript (how to register events, retrieve DOM objects, manipulate CSS, etc.) and you will find web programming much more enjoyable (not to mention easier). A lot of people mentioned different Ajax libraries, but I didn't see any actual Ajax examples, so here it goes. (If you are not familiar with Ajax, all it is, is making an asynchronous HTTP request to refresh content (or perhaps perform a server-side action in your scenario) without reloading the entire page or doing a full postback.
Client-Side:
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest(); // Create object that will make the request
xmlhttp.open("GET", "http://example.org/api/service", "true"); // configure object (method, URL, async)
xmlhttp.send(); // Send request
xmlhttp.onstatereadychange = function() { // Register a function to run when the state changes, if the request has finished and the stats code is 200 (OK). Write result to <p>
if (xmlhttp.readyState == 4 && xmlhttp.statsCode == 200) {
document.getElementById("resultText").innerHTML = xmlhttp.responseText;
}
};
</script>
That's it. Although the name can be misleading the result can be in plain text or JSON as well, you are not limited to XML. jQuery provides an even simpler interface for making Ajax calls (among simplifying other JavaScript tasks).
The request can be an HTTP-POST or HTTP-GET and does not have to be to a webpage, but you can post to any service that listens for HTTP requests such as a RESTful API. The ASP.NET MVC 4 Web API makes setting up the server-side web service to handle the request a breeze as well. But many people do not know that you can also add API controllers to web forms project and use them to handle Ajax calls like this.
Server-Side:
public class DataController : ApiController
{
public HttpResponseMessage<string[]> Get()
{
HttpResponseMessage<string[]> response = new HttpResponseMessage<string[]>(
Repository.Get(true),
new MediaTypeHeaderValue("application/json")
);
return response;
}
}
Global.asax
Then just register the HTTP route in your Global.asax file, so ASP.NET will know how to direct the request.
void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapHttpRoute("Service", "api/{controller}/{id}");
}
With AJAX and Controllers, you can post back to the server at any time asynchronously to perform any server side operation. This one-two punch provides both the flexibility of JavaScript and the power the C# / ASP.NET, giving the people visiting your site a better overall experience. Without sacrificing anything, you get the best of both worlds.
References
Ajax,
jQuery Ajax,
Controller in Webforms
The Microsoft AJAX library will accomplish this. You could also create your own solution that involves using AJAX to call your own aspx (as basically) script files to run .NET functions.
This is the library called AjaxPro which was written an MVP named Michael Schwarz. This was library was not written by Microsoft.
I have used AjaxPro extensively, and it is a very nice library, that I would recommend for simple callbacks to the server. It does function well with the Microsoft version of Ajax with no issues. However, I would note, with how easy Microsoft has made Ajax, I would only use it if really necessary. It takes a lot of JavaScript to do some really complicated functionality that you get from Microsoft by just dropping it into an update panel.
It is so easy for both scenarios (that is, synchronous/asynchronous) if you want to trigger a server-side event handler, for example, Button's click event.
For triggering an event handler of a control:
If you added a ScriptManager on your page already then skip step 1.
Add the following in your page client script section
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
Write you server side event handler for your control
protected void btnSayHello_Click(object sender, EventArgs e)
{
Label1.Text = "Hello World...";
}
Add a client function to call the server side event handler
function SayHello() {
__doPostBack("btnSayHello", "");
}
Replace the "btnSayHello" in code above with your control's client id.
By doing so, if your control is inside an update panel, the page will not refresh. That is so easy.
One other thing to say is that: Be careful with client id, because it depends on you ID-generation policy defined with the ClientIDMode property.
I'm trying to implement this but it's not working right. The page is
posting back, but my code isn't getting executed. When i debug the
page, the RaisePostBackEvent never gets fired. One thing i did
differently is I'm doing this in a user control instead of an aspx
page.
If anyone else is like Merk, and having trouble over coming this, I have a solution:
When you have a user control, it seems you must also create the PostBackEventHandler in the parent page. And then you can invoke the user control's PostBackEventHandler by calling it directly. See below:
public void RaisePostBackEvent(string _arg)
{
UserControlID.RaisePostBackEvent(_arg);
}
Where UserControlID is the ID you gave the user control on the parent page when you nested it in the mark up.
Note: You can also simply just call methods belonging to that user control directly (in which case, you would only need the RaisePostBackEvent handler in the parent page):
public void RaisePostBackEvent(string _arg)
{
UserControlID.method1();
UserControlID.method2();
}
You might want to create a web service for your common methods.
Just add a WebMethodAttribute over the functions you want to call, and that's about it.
Having a web service with all your common stuff also makes the system easier to maintain.
If the __doPostBack function is not generated on the page you need to insert a control to force it like this:
<asp:Button ID="btnJavascript" runat="server" UseSubmitBehavior="false" />
Regarding:
var button = document.getElementById(/* Button client id */);
button.click();
It should be like:
var button = document.getElementById('<%=formID.ClientID%>');
Where formID is the ASP.NET control ID in the .aspx file.
Add this line to page load if you are getting object expected error.
ClientScript.GetPostBackEventReference(this, "");
You can use PageMethods.Your C# method Name in order to access C# methods or VB.NET methods into JavaScript.
Try this:
if(!ClientScript.IsStartupScriptRegistered("window"))
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "window", "pop();", true);
}
Or this
Response.Write("<script>alert('Hello World');</script>");
Use the OnClientClick property of the button to call JavaScript functions...
You can also get it by just adding this line in your JavaScript code:
document.getElementById('<%=btnName.ClientID%>').click()
I think this one is very much easy!
Please try this:
<%= Page.ClientScript.GetPostBackEventReference(ddlVoucherType, String.Empty) %>;
ddlVoucherType is a control which the selected index change will call... And you can put any function on the selected index change of this control.
The simplest and best way to achieve this is to use the onmouseup() JavaScript event rather than onclick()
That way you will fire JavaScript after you click and it won't interfere with the ASP OnClick() event.
I try this and so I could run an Asp.Net method while using jQuery.
Do a page redirect in your jQuery code
window.location = "Page.aspx?key=1";
Then use a Query String in Page Load
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["key"] != null)
{
string key= Request.QueryString["key"];
if (key=="1")
{
// Some code
}
}
}
So no need to run an extra code
This reply works like a breeze for me thanks cross browser:
The __doPostBack() method works well.
Another solution (very hackish) is to simply add an invisible ASP button in your markup and click it with a JavaScript method.
<div style="display: none;">
<asp:Button runat="server" ... OnClick="ButtonClickHandlerMethod" />
</div>
From your JavaScript, retrieve the reference to the button using its ClientID and then call the .Click() method on it:
var button = document.getElementByID(/* button client id */);
button.Click();
Blockquote

Categories

Resources