My aspx page:
<asp:TableCell>
<asp:TextBox ID="tbFirstName" ClientIDMode="Static" runat="server" onblur="javascript:CheckFirstNameInput(this)">
</asp:TextBox>
</asp:TableCell>
My C# class
[ScriptService()]
public static class InputChecks
{
[WebMethod()]
[ScriptMethod()]
public static bool CheckForLettersSpacesStripes(string input)
{ //SomeCode }}
My masterpage
<asp:ScriptManager runat="server" ID="smScriptManager" EnablePageMethods="true">
<Scripts>
<!-- And some standard imported scripts -->
<asp:ScriptReference Path="~/Resources/JavaScriptFunctions.js" />
</Scripts>
</asp:ScriptManager>
As you might notice, the idea is that I import a javascript here, which works fine. Tested it out with an alert and several console.logs and stuff. But I can't reach the C# methods, I used several stuff. I used an ajax call:
function CheckFirstNameInput(InputElement)
{
var Input = InputElement.value;
console.log(Input);
$.ajax({
url: "Test",
data: "{input : " + Input + "}",
success: function(response)
{
alert(response.url);
}
});
}
But also I just used PageMethods. None of the above worked, I tried placing the scriptmanager in the aspx page instead of the masterpages, didn't work out. I am completely out of ideas, and I am not finding any new stuff on the net. So, is there anyone who knows the answer, I would be eternally gratefull for the answer which releases me from this annoying burden.
You need to change the URL
change url: "Test", to url: "Application Path /CheckForLettersSpacesStripes",
or try another one way by using PageMethods
You don't need any lines , just try this code instead of your code
PageMethods.CheckForLettersSpacesStripes(input);
referred from
Related
I want to get access to a method in code behind when I clicked an span in my view aspx:
DEFAULT.ASPX VIEW CODE:
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<%-- MY SPAN --%>
<span runat="server" onclick="ShowChartSpider(this.id)" id="group_2" style="cursor: pointer" class="pull-right">My Span</span>
<%-- JAVASCRIPT CODE --%>
<script type="text/javascript">
function ShowChartSpider(group_id) {
$.ajax({
type: "POST",
url: "Default.aspx/MethodToCreateChart",
dataType: "json",
data: "{'parameter1':" + JSON.stringify(group_id) + "}",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("all correct");
},
error: function (data) {
alert("no");
}
}
);
}
</script>
</asp:Content>
DEFAULT.ASPX.VB CODE BEHIND:
<WebMethod()>
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
Public Shared Sub MethodToCreateChart(sender As Object, e As EventArgs)
' My code to create the chart .....
End Sub
if I run the page, and inspects the page with the browser to see errors, none appear, but the code does not reach the breakpoint that I put in the method in codebehind.
What I´m doing wrong?
I would appreciate suggestions, thanks.
First check your server allow non HTTPS request.
i had that type of issue and my server didn't allow me to do that.
it so then disable that and test.
Then check the response status.
error: function(xhr, status) {
alert(xhr.status); }
let us know that is the outcome.
--Ruhul
Go to "RouteConfig.vb" under "App_Start" folder.
Change following line
settings.AutoRedirectMode = RedirectMode.Permanent
To
settings.AutoRedirectMode = RedirectMode.Off
i think your method code returning something like this.
Return Default.aspx/MethodToCreateChart
so me your MethodToCreateChart logic.
you can try with below sample method. your internal server error are coming because you are returning somethng from your method.
Public Shared Function MethodToCreateChart(parameter1 As String) As String
Return "Hello " & Environment.NewLine & "The Current Time is: " & _DateTime.Now.ToString()
End Function
I think you should remove 'runat=server' attribute from span tag.
You use aspx file same as ashx files. So have a look at below links:
1. How do you debug ASP.net HTTPHandler
2. Can't debug ASHX handler
I have a page which displays the following content when it is loaded:
<div>
<img src="loading.gif" alt="Loading" /> Generating PDF Document, please wait.
<div>
At the same time, I want to run this method the code behind automatically:
private void GeneratePdf()
{
...
}
Lastly, I want to redirect the user to the File.pdf path once the GeneratePdf() method is completed.
How do I do this?
You need to use the Page_Load event as explained here. Additionally, this is a great explanation of the page life cycle. You should take a look at it. Here is some sample code from the above link:
<script runat="server">//This script runs on the server and dishes up some output for the page.
Sub Page_Load
lbl1.Text="The date and time is " & now()
End Sub
</script>
<html>
<body>
<form runat="server">
<h3><asp:label id="lbl1" runat="server" /></h3>//This generates the textbox that will be given a value from the above script.
</form>
</body>
</html>
Hope this helps you!
I suggest to use GeneratePDF with ajax, so you can use like
$.ajax({
url: '/pdf/fiele_to_generate_pdf.aspx',
type: 'POST',
contentType: "application/json; charset=utf-8",
data: $.toJSON(jsonObj),
processData: false,
dataType: 'html',
async: false,
success: function(html) {
window.location.href = '/pdf/example.pdf';
}});
so for loading you can use jquery, there is a good plugin named BlockUI you can use it before your ajax call.
You can use the asp:Timer control to indicate when your code-behind should be called
<asp:Timer runat="server" ID="timer1" Interval="3000" OnTick="timer1_Tick"></asp:Timer>
Then implement the Timer's Tick event. This will be called after 3 seconds (3000ms) as specified in the markup
protected void timer1_Tick(object sender, EventArgs e)
{
GeneratePdf();
Response.Redirect("~/somepath/generatedPDF.pdf");
}
This is my JavaScript:
$(document).ready(function () {
function ShowHelp() {
window.open('../WebHelp/' + '<%= SessionManager.CurrentDictionaryId %>' + '/mweb.htm#cshelp/assetsdetail.htm', '', 'toolbar=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes');
}
function RunPrint(values) {
window.open('../Reports/Assets/AssetProfile.aspx?id=' + values, '', 'toolbar=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes');
}
});
And I have two <asp:Hyperlink> tags set like this:
<asp:HyperLink ID="lnkHelp" runat="server" EnableViewState="False" ImageUrl="~/Images/Help.png"
NavigateUrl="javascript:ShowHelp();" />
<asp:HyperLink ID="lnkPrint" ImageUrl="~/Images/PrintMed.png" runat="server" EnableViewState="false"
NavigateUrl="javascript:GetSelectedToPrint();" />
When running the debugger tools in Chrome I get the message:
"Uncaught ReferenceError: ShowHelp is not defined"
"(anonymous function)"
I am fairly ignorant in javascript, but I feel like I know enough to read what is there and i don't see the issue.
did you try to remove the $(document).ready(function(){ ?
that code is not needed if you are just wanting to create a function that will be fired after the controls were loaded (which is in your case).
Hello how i can load web forms inside one web forms div/
SO i have web form 'account' which opening inside master page.
on my account web form i have menu i want when user clicks it to load another web form inside account page.
I am using ASP.NET C#.
Sorry For My Bad English.
Thanks
If you want to do this server-side this can be accomplished by loading an instance of a usercontrol into your form vs. the actual page. Click here to see an MSDN example and be sure to use update panels to manage the post backs.
If you want to do this client side you can do so via ajax and calling an ashx (handler file)
To manage this client side:
within your aspx file add the following:
within the header
<script type="text/javascript">
$(function () {
$("#panel").hide();
});
$(document).ready(function () {
$(".slide").click(function () {
$("#panel").show("slow", false);
jQuery.ajax({
type: "POST",
url: "controlloader.ashx",
dataType: "html",
success: function (response) {
jQuery('#loadcontrol1').append(response);
},
error: function () {
jQuery('#loadcontrol1').append('error');
}
});
});
});
</script>
And then within the body
<body>
<form id="form1" runat="server" >
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<div id="panel" >
<p>stuff here</p>
</div>
<p><%= DateTime.Now %></p>
<div id="div1" class="slide">
<p class="btn-slide">Expand Panel</p>
</div>
<br />
<asp:Button Text="Click me" ID="clickButton" runat="server" />
<div id="loadcontrol1" />
</div>
</form>
</body>
Then within your ashx file
public class controlloader : IHttpHandler
{
//If annonymous id is turned on IRequireSessionState Interface may be needed to write session variabled such as user auth.
// Generic handlers by default implementIReadOnlySessionState
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write(RenderPartialToString("~/Control1.ascx")); ;
}
private string RenderPartialToString(string controlname)
{
Page page = new Page();
Control control = page.LoadControl(controlname);
page.Controls.Add(control);
StringWriter writer = new StringWriter();
HttpContext.Current.Server.Execute(page, writer, false);
return writer.ToString();
}
public bool IsReusable
{
get
{
return false;
}
}
}
You will also need to create the user control file but I'll leave that code to you.
There are a few things happening in this example. The button is used to proveout post-backs to ensure the control is not reloaded. I also added an animation which you don't need but this was an old proof-of-concept piece I had from a while back so you can ignore that chuck of code.
I know you mentioned the user of master pages so you will more than likely want to factor out the javascript into a js file and then be sure to load it using script manager as:
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Scripts>
<asp:ScriptReference Path="~/js/jquery-1.7.js" />
<asp:ScriptReference Path="~/js/yourcontrolloader.cs" />
</scripts>
</asp:ScriptManager>
This is required when using master pages otherwise due to the server side rendering your references will be lost and the scripts never called. You could also use a partial reference in the actual page vs the masterpage but this is up to you.
Best of luck
In a simple ASP page, TextBox AutoPostBack events will prevent Button click events (except where button is tapped very quickly) and AutoPostBack events for other controls (like ListBox).
There's a similar question here, but I wasn't happy with being forced to use client side or AJAX solutions: Have to click button twice in asp.net (after autopostback textbox)
Example ASPX page:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="temp.aspx.cs" Inherits="temp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" OnTextChanged="PostBack"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="PostBack" Text="Button" /><br />
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="PostBack">
<asp:ListItem>value1</asp:ListItem>
<asp:ListItem>value2</asp:ListItem>
</asp:ListBox><br />
<br />
Events Fired:<br />
<asp:TextBox ID="TextBox2" runat="server" Height="159px" TextMode="MultiLine" Width="338px"></asp:TextBox></div>
</form>
</body>
</html>
C# code behind:
public partial class temp : System.Web.UI.Page
{
protected void PostBack(object sender, System.EventArgs e)
{
this.TextBox2.Text += string.Format("PostBack for - {0}\n", ((System.Web.UI.Control)sender).ID);
}
}
I've been able to partially solve this problem for buttons by using mousedown instead of click events to submit the form (I also blocked extra AutoPostBack events client-side and handled any extra field changes during button click events server side)
However, this means my buttons aren't quite behaving in the standard (click on release) way.
Is there a better solution to this problem that doesn't require trying to do everything in javascript client-side? (I'm writing a lot of code that reads server data during these postbacks, so javascript isn't an ideal solution.)
I'm also trying to avoid switching to an AJAX library for these pages since every new library I add has to go through security auditing etc.
Note: I'm currently working with ASP.Net 2.0/VS 2005, but if this type of problem is fixed in a later release that would be a compelling argument to upgrade. (As far as I understand it, the same problem seems to happen in ASP.Net 4/VS 2010)
The reason to set AutoPostBack="true" on a field (or other input control) is because you want the page to postback when that control's data changes - without requiring that the user click a button. It sounds like that is exactly what is happening: when the field loses focus, the page does a postback.
Perhaps I'm misunderstanding the question? Can you provide some more information about how you need the page/form to behave?
Edit: more info, based on comment from OP.
I think I understand: the "normal" case is they select something from a DropDownList1, and you autopostback to set the values of DropDownList2, based on the selected item in DropDownList1. However, the user may not care about the second list; if they click "search", you want the button-click to essentially abort the autopostback (already in progress), and initiate a new postback.
Unfortunately, I don't think there's any functionality in any version of ASP.NET to "abort" a postback already in progress (not from the client-side code, anyway). Therefore, in order to implement the above behavior, you're going to have to do something outside the standard ASP.NET postback behavior. Here's a few ideas, though by no means is it an exhaustive list:
Use AJAX and JS to retrieve the contents of DropDownList2. If the user clicks search while that ajax call is in progress, the page should postback right away.
Store all possible DropDownList2 data in JSON format in your page; use purely client-side JS to populate List2 when List1 changes. Again, if the user clicks "search", the page will postback right away. Depending on how big the pool of possible List2 entries is, this may bloat the page size too much to be workable.
Use client-side JS to disable your search button when List1 changes selection. The user won't be able to click "search" until the autopostback (to fill List2) completes.
Hope this helps!
To make the client side be more interactive and reduce sending all that viewstate and redrawing the page, I add a little jquery into the mix. It makes things like what you are proposing possible. jquery even ships with the asp.net MVC framework so there is no shame in using it with asp.net.
Here is a simple example that uses jquery that demonstrates what I think you want.
First, in the aspx file, add in a reference to the jquery library. I use the
Google content delivery network so you don't even have add this file to your VS project.
Then take the auto postback references out of all your server controls except the button. I left that one to continue doing a postback because I suspect at some point you want a regular post back, all the other controls use ajax to get your server side response.
I started by using your example page with these modifications:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="temp.aspx.cs" Inherits="temp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function () {
// Establish where the output goes.
var outputObject = $("#<%=TextBox2.ClientID %>");
// create a function to do an ajax postback
function doAjaxPostback(sender, value) {
$.ajax({
type: "POST",
url: "temp2.aspx",
data: "id=" + sender.attr("id") + "&value=" + value,
success: function (data) { outputObject.append("<br />" + data) }
});
}
// Use jquery to wire up the event handler. We use the ClientID property in case these
// elements get embeded in some other server control container later.
$("#<%=TextBox1.ClientID %>").keyup(function (event) { doAjaxPostback($(this), $(this).val()); });
$("#<%=TextBox1.ClientID %>").change(function (event) { doAjaxPostback($(this), $(this).val()); });
$("#<%=ListBox1.ClientID %>").change(function (event) { doAjaxPostback($(this), $(this).val()); });
// Use a plain html button tag for ajax only. The server control button gets rendered as
// a submit button which requires it to be handled a little differently.
$("#PlainButton").click(function (event) { doAjaxPostback($(this), $(this).attr("value")); event.preventDefault(); });
});
</script>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="PostBack" Text="Button" /><br />
<button id="PlainButton" value="Plain Old Button">Ajax Only, No postback</button>
<br />
<asp:ListBox ID="ListBox1" runat="server" >
<asp:ListItem>value1</asp:ListItem>
<asp:ListItem>value2</asp:ListItem>
</asp:ListBox>
<br />
<br />
Events Fired:<br />
<asp:TextBox ID="TextBox2" runat="server" Height="159px" TextMode="MultiLine" Width="438px"></asp:TextBox>
</div>
</form>
</body>
</html>
Then for the code behind I just made a tiny change so we can report when we get a regular postback versus the ajax kind:
protected void PostBack(object sender, System.EventArgs e)
{
this.TextBox2.Text += "\n\nGot an asp.net postback\n\n"
+ string.Format("PostBack for - {0}\n", ((System.Web.UI.Control)sender).ID);
}
Okay, so I was trying not to get too fancy but I wanted to demonstrate how easy this is so I made a second page, temp2.aspx but left the aspx file alone as i only needed what is in the code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class temp2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string id = string.Empty;
string value = string.Empty;
Response.Clear();
if (Request.Form == null || Request.Form.Count < 1)
{
Response.Write("I got nothin'");
Response.Flush();
Response.End();
return;
}
id = Request.Form["id"];
value = Request.Form["value"];
Response.Write(string.Format("\nevent from: {0}; value={1}",id,value));
Response.Flush();
Response.End();
}
}
}
Notice that what I did was clear, write, flush and end the response so only the text we want is sent back to the caller. We could have done some fancy stuff in the page_load of the original temp page to check if it is a call from the ajax function that will not clear or flush the response if the incoming Request.Form does not contain a certain field, etc. But by doing it as a separate page, I hoped to simplify the code. This also opens up possibilities.
Say you have a country drop down that has Canada and USA in it and when it changes, you want to sent back data to populate a State/Province dropdown with the appropriate values. By putting the lookup code on its own page the way I did with temp2.aspx, you can then call it from all the pages in your app that have a need for such a service.
Good luck, let me know if you have any trouble understanding my code.