PageMethods Not Working with VS2013 web application - javascript

I have spent all day struggling with this Error and have read almost every article and tried every hint I found but still not able to make it work.
Please Note: EnablePageMethod=true inside ScriptManager, Method is public and static and decorated with [WebMethods]
Same coding is working all perfect with VS2010 and with empty project in VS2013 but when using with New Project -> web -> web forms the output is attached here for your reference.
Here is my code.
Code Behind:
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
JavaScript:
<script type="text/javascript">
function ShowCurrentTime() {
PageMethods.GetCurrentTime(document.getElementById("<%=txtUserName.ClientID%>").value, OnSuccess);
}
function OnSuccess(response, userContext, methodName) {
alert(response);
}
</script>
HTML:
<div>
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()" />
</div>

Try adding both [System.Web.Services.WebMethod] and [System.Web.Script.Services.ScriptMethod] to the server side GetCurrentTime method.
Also make sure your script manager has EnablePageMethods="True". Your question states you set EnablePageMethod=true which is incorrectly spelled (should be plural).

You need to fail the click event handler to prevent the postback/page submit.
Just return false from your javascript function:
function ShowCurrentTime() {
PageMethods.GetCurrentTime(document.getElementById("<%=txtUserName.ClientID%>").value, OnSuccess);
return false; // added
}

You have to make sure that the button does not post back when calling a PageMethod from client-side. With your current markup, it will post back and cause unexpected effects.
You should be using the following markup for button, so it never posts back. Then the call to pagemethod should work. In markup below the button click event is returning a false value, so the page never gets submitted i.e. posted back.
Also, it would be best if you post your page markup in full, since there may be an issue with the markup.
<input id="btnGetTime" type="button" value="Show Current Time"
onclick="ShowCurrentTime();return false;" />

Related

execute javascript after download a file (RegisterStartupScript)

I want to execute a RegisterStartupScript calling a Javascript function after certain processes happen in my code behind. It is basically a Loading loop decoration made in CSS3. I show it (with javascript) on buttons clientclick, when I know the process will take a while and I hide it when the process is finished. Everything works fine, but now I have a process in Which I download a file using another empty webform using response.redirect. The file is downloaded fine, but the RegisterStartupScript call does not work. I understand the response is the problem, but nor I need to work in a workaround to solve this (I do not want to change the whole way, cause it is implemented in many other pages and processes. I wil provide the related code (not all), in case you can give me a direct way to solve it.
Javascript
function LoadingLoopOn()
{
$('#outerAlignId').addClass("outerAlign");
$('#middleAlignId').addClass("middleAlign");
$('#innerAlignId').addClass("innerAlign");
$('#OutterCircleId').addClass("OutterCircle");
$('#InnerCircleId').addClass("InnerCircle");
$('#Loadinglbl').addClass("LoadingLabelStyle");
}
function LoadingLoopOff()
{
$('#outerAlignId').removeClass("outerAlign");
$('#middleAlignId').removeClass("middleAlign");
$('#innerAlignId').removeClass("innerAlign");
$('#OutterCircleId').removeClass("OutterCircle");
$('#InnerCircleId').removeClass("InnerCircle");
$('#Loadinglbl').removeClass("LoadingLabelStyle");
}
HTML (it is on the master page, to be able to used it in every webform)
<asp:Panel ID="outerAlignId" ClientIDMode="Static" runat="server" CssClass="outerAlign">
<div id="middleAlignId" class="middleAlign">
<div id="innerAlignId" class="innerAlign">
<div id="OutterCircleId" class="OutterCircle"></div>
<div id="InnerCircleId" class="InnerCircle"></div>
<asp:Label ID="Loadinglbl" ClientIDMode="Static" runat="server" Text="Loading..." CssClass="LoadingLabelStyle"></asp:Label>
</div>
</div>
</asp:Panel>
HTML Button Sample Where I want to used it
<asp:ImageButton ID="ExportExId" ClientIDMode="Static" runat="server" OnClientClick="LoadingLoopOn();" OnClick="ExportExId_Click" CssClass="..." ImageUrl="..." />
And the CS# Code behind
protected void ExportExId_Click(object sender, ImageClickEventArgs e)
{
//...
//Many code and DB treatment goes here, to finally get a temporally Excel file in the server
//..
//I call the page with the file name and path
Response.Redirect(String.Format("DownloadForm.aspx?FileName={0}&Path={1}", fileExported.Name, "Temp" + UserName));
//This piece of code must be excuted in its webform after the redirect (once ee finished)
ScriptManager.RegisterStartupScript(this, GetType(), "LoadingLoopOff", "LoadingLoopOff();", true);
}
As I marked in my comment, A possible solution could be AJAX. Make an ajax call to force a page update and then the function would be processed (on the load), or directly call the function through this ajax call. The problem is that I do not know how to uise AJAX in this case...
Many thanks,

Unable to call javascript in CSHTML

I am pretty new to MVC. I am trying to call a javascript function from a view page (button click) but I am unable to call it .I have the javascript function in a seperate file .I have added the reference of the script file in the view page(CSHTML).
Code:
<input type="submit" value="enter" onclick="IsFirstNameEmpty();">
Javascript Function
function IsFirstNameEmpty() {
if (document.getElementById('TxtFName').value == "") {
return 'First Name should not be empty';
}
else { return ""; }
}
Simple example : https://jsfiddle.net/8mhuL839/
You do everything fine (I trust your words about You've correctly included js-file). But You just doesn't do anything with your returned string.
In my example I just put text into alert-dialog.
Maybe you want to show this text in some label, then just do next :
document.getElementById('LblValidation').value = returnedText;
where LblValidation is Id of some Label that will contains your string, and returnedText is string that you try to return from your function.
<input type="submit" value="enter" onclick="IsFirstNameEmpty();"/>
<input type="text" value="text" id="TxtFName" />
<script type="text/javascript" >
function IsFirstNameEmpty() {
if (document.getElementById('TxtFName').value == "") {
alert( 'First Name should not be empty');
}
else { alert(""); }
}
</script>
In general, there is no difference between what you did without the mvc paradigm. Pay only attention to the fact that if the script is inside a partial page it could be executed more than once or not in the moment you expect (for example you could call a function before it is defined because of the partial views loading order). In this simple scenario, I think you have just to be sure that the script containing the definition of the function is really included in the resulting web page. The simplest way to do this is by checking the page source in the browser.

Extracting user entry from text box and storing it in a variable in javascript

// text Box
<asp:TextBox ID="TextBox3" runat="server" BackColor="Silver"
BorderColor="Silver" ontextchanged="TextBox3_TextChanged"
style="margin-left: 6px" Width="154px"></asp:TextBox>
// Submit button
<asp:Button ID="Button6" runat="server" BackColor="Silver"
onClientclick='store_memID()' style="margin-left: 20px" Text="Submit"
Width="102px" Font-Bold="True" Height="28px" />
<script type = "text/javascript">
// Function to caputure client-input- Member_ID.
function store_memID() {
var mem_ID = document.getElementById('TextBox3').value;
return confirm('TimeLine is displayed for: ' + mem_ID);
}
</script>
When I run the code and enter a value into the text box and then press the submit button:-
"Microsoft JScript runtime error: Unable to get value of the property 'value': object is null or undefined".
Else, if I remove the '.value' :-
<script type = "text/javascript">
// Function to caputure client-input- Member_ID.
function store_memID() {
var mem_ID = document.getElementById('TextBox3');
return confirm('TimeLine is displayed for: ' + mem_ID);
}
</script>
and then run the program, enter value in text box and press submit then i get :-
"TimeLine is displayed for: Null"
I have been looking into solving this problem. not sure whats going wrong...
Edit (fix):- Server Side ID for my text box is 'TextBox3' but this doesn't necessarily match up with the client side ID.
to get Client Side ID:- '<%=TextBox3.ClientID%>'
It's been a while since I wrote asp forms but it is likely that the id on the client side (in your browser) is not what you think it is. This is/was one of the major pitfalls of web forms in my mind (This may have been made simpler in version 4.0, you'll have to check that). You could use a css class (and use jQuery or similar to find your element) or inject the client side id into the java script e.g.;
<script type = "text/javascript">
// Function to caputure client-input- Member_ID.
function store_memID() {
var mem_ID = document.getElementById('<%=TextBox3.ClientID%>').value;
return confirm('TimeLine is displayed for: ' + mem_ID);
}
</script>
UPDATE: fixed case error in ClientID as pointed out in comments
You are using asp Text Boxes which are mostly used for server side code. The ID you place in the tag is not guaranteed to match the ID of the element rendered.
You will need to inspect your html in the browser to find the rendered ids. (Likely will look something like: ct100_TextBox3) and use that instead. Or, if you are not doing any server side coding, it would probably be best to convert your text boxes to <input /> fields, or <textarea />.

Unable to call a function while using master page in Javascript at checkbox checked change event

I was trying to call a function when the checkbox status changes, it calls without a masterpage. I have tried the following code:
<script type="text/javascript">
$(function () {
$('#cbOption1').on('change', PublishToPreferredZerker);
});
function PublishToPreferredZerker() {}
</script>
[...]
<asp:CheckBox ID="cbOption1" runat="server" style="text-align: left"
Text="Publish the job to particular Zerker or a group of the Zerkers." /><br />
The function is not called when using MasterPage.
Note cbOption1 is not the client ID, but the ID for the server side.
You need to do something like (Use Control.ClientID Property to get the id for HTML element):
$('#<%=cbOption1.ClientID%>').on('change', PublishToPreferredZerker);
The code
$('#cbOption1').on('change', PublishToPreferredZerker);
finds the control with id cbOption1 and then acts on that control
But when using this code on a master page, the control id does not remain cbOption1.
It is prefixed by master page content Id.
something like ct$001cbOption1
To make it work when using master pages use code like this to find the clientId for the control :
$(#"<%= cbOption1.ClientID %>").on( .... )
I got success while I added below code on Page load function.
cbOption1.Attributes.Add("onChange", "javascript:PublishToPreferredZerker()");
Javascript function
function PublishToPreferredZerker() {}
Also I have tried above answers but not get required output.
Thanks,

BUTTON ONCLICK ONSERVERCLICK

I am facing a problem with buttons.
I want a client side validation to occur(say selecting a maximum of only 4 checkboxes in a datalist).
I used a INPUT TYPE="BUTTON" RUNAT="SERVER" style of tag. and put Onserverclick="someservermethod" which works fine.
I wrote a Validate() and added onclick="return validate();" to the above HTML markup and was thinking if it returns false then my server side code someservermethod() would not execute and it works great as expected
But when I return true I thought it would fire my someservermethod(), but it is not working. Any thoughts on why it is not working?
HTML MARKUP BELOW FOR THE BUTTON
button onclick="return ValidateSelection();" type="button" id="btnSubmit"
runat="server" onserverclick="btnSubmit_Click"
JAVASCRIPT CODE
function ValidateSelection()
{
if(good)
{
// I expect that my server side code btn_Submit would have got called. But
// it doesn't get called.
return true;
}
else
{
//This works great. Not calling the server side method for the button
alert('something happened');
return false;
}
}
I think I am messing up with the formatting. Pardon me.
The control you are using right now it HtmlButton which is not "fit" for what you are trying to do, as your onclick overwrites the required client side code for the post back.
What you need is the Button control which does support overwriting the client side onclick and still perform the post back as usual.
Change the markup to this and it should work:
<asp:button OnClientClick="return ValidateSelection();" id="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit"></asp:Button>

Categories

Resources