I need a ASP.net application which is only kind of "pageDisplayer" from content which is coming from an API. So I choose ASP.net Webform and tried the following:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="PMLetterAcceptance.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:Literal runat="server" id="JavaScript"></asp:Literal>
</head>
<body>
<form id="letterform" runat="server">
<div>
<%= pageContent %>
</div>
</form>
</body>
public partial class WebForm1 : System.Web.UI.Page
{
protected string pageContent = "";
protected void Page_Load(object sender, EventArgs e)
{
...// here I fetch the html and javascript content from the API
dynamic json = Json.Decode(streamReader.ReadToEnd());
if (json.status != "OK")
pageContent = json.error;
else
pageContent = json.html;
JavaScript.Text = json.script;
}
}
The html content and the script are loaded correct but I cannot access DOM elements in the javascript. The javascript looks like that
(function()
{
function processForm(e)
{
... // Here I want to do some stuff before sending the form
}
let form = document.getElementById('letterform');
if (form.attachEvent)
form.attachEvent("submit", processForm);
else
form.addEventListener("submit", processForm);
})();
No I get the error "form is null". For me it looks like the javascript is executed before the DOM is ready. But how can I change this to make it work like expected?
Try putting the JS (literal) at the bottom of the page, before the closing body tag. That way, the HTML will be loaded before the JS tries to find elements.
Related
I am trying to build a progressbar trying to periodically run an ajax call from the client side while a postback is occuring.
However, it seems like the ajax call gets blocked, maybe because of to the postback. When the postback is finished, the http request with the ajax calls goes from pending to canceled.
Questions:
Is it impossible to issue ajax calls during postback?
Can I use the Session like I am doing in the following code example to keep track of the progress?
The webpage aspx:
<%# Page Language="C#" AutoEventWireup="true"
CodeBehind="TestProgressIndicator.aspx.cs"
Inherits="Test.TestProgressIndicator" %>
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-3.2.1.min.js"
type="text/javascript"></script>
<script type="text/javascript">
function start_progress()
{
var indicator = $(".progress-indicator");
indicator.show();
var num_div = indicator.find(".num");
num_div.text("0%");
setTimeout(update_progress, 80);
function update_progress()
{
console.log("update_progress");
$.post(
"Ajax/ProgressBarCallback.aspx"
, function (progress)
{
num_div.text(progress + "%");
if (progress < 100)
setTimeout(update_progress, 80);
else
indicator.hide();
});
}
}
</script>
</head>
<body>
<form runat="server">
<asp:ScriptManager runat="server"/>
<div class="progress-indicator">
<div class="num"></div>
</div>
<asp:Button ID="btnStart" runat="server" Text="Starta"
OnClientClick="start_progress()" OnClick="btnStart_OnClick" />
</form>
</body>
</html>
Ajax/ProgressBarCallback.aspx:
<%# Page Language="C#" %>
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
var progressObj = HttpContext.Current.Session["progress"];
var progress = progressObj != null ? int.Parse(progressObj.ToString()) : 0;
Response.ContentType = "text/json";
Response.Write(progress);
}
</script>
I am aware of this post being a duplicate of ASP.NET making AJAX calls during long Postback but it was 5 years since asked and it did not get any explanatory answers.
The textbox is defined as html input text type and takes input from the users. This value is needed to pass as key to hashtable defined in aspx.cs file being used in aspx file. But the correct value is not being given and an exception is being thrown. Any help in this regard would be helpful. Thanks
The code is as follows:
<% =Hashtable[document.getElementbyId("Textbox").Value]%>
document.getElementbyId("Textbox").Value is not giving the correct output. If it is replaced by a string value acting as key then it works fine. The only problem is getting the string value from textbox.
First include jquery in head section
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
Try below code to read textbox value :
First read text box value using
var key = $("[id$=Textbox]").val();
and see if value is present in texbox if present use this to read hash value
<% =Hashtable[key]%>
Try this it worked for me :
aspx :
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script>
function GetHashtable() {
alert("<% = hashtable[this.test] %>");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtKey" OnTextChanged="txtKey_TextChanged" AutoPostBack="true" runat="server"></asp:TextBox>
</div>
</form>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
</body>
</html>
Code behind :
public partial class _Default : System.Web.UI.Page
{
protected int test;
public Hashtable hashtable = new Hashtable();
static Hashtable sHashtable = new Hashtable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
sHashtable[1] = "One";
sHashtable[2] = "Two";
sHashtable[13] = "Thirteen";
}
}
protected void txtKey_TextChanged(object sender, EventArgs e)
{
test = Convert.ToInt32("0" + txtKey.Text);
hashtable = sHashtable;
Page.ClientScript.RegisterStartupScript(this.GetType(), "GetHashtable", "GetHashtable();", true);
}
}
I want to read the Page(.aspx) Hiddenfield Value in the User Control that is placed on that Page and process some logic.
FOr eg: I have a hidden field x on a Page. The Page has many user controls and I want to access this hidden field (x) in those User Controls where value of x will be set by a Javascript in the Page.
I am trying to find the HiddenControl and read its value from codebehind of usercontrol(.ascx.cs) but always get null.
HiddenField colname = UIUtils.FindControlRecursive(this.Parent.Page, "MainContent_AssignedTo_ColName") as HiddenField;
The ID is same as the hiddenfield on client Side. I tried this.Parent and this.Parent.Parent for the first argument too but no luck.
what am I missing here.
Here is my aspx page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestFindControl._Default" %>
<%# Register Src="ReadHiddenField.ascx" TagName="Assign" TagPrefix="uc1" %>
<!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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:HiddenField ID="HiddenField1" runat="server" Value="10">
</asp:HiddenField>
<asp:placeholder ID="Placeholder1" runat="server"><uc1:Assign id="test" runat="server"></uc1:Assign> </asp:placeholder>
</div>
</form>
</body>
</html>
and here is my code behind on control:
protected void Page_Load(object sender, EventArgs e)
{
HiddenField test = (HiddenField)Page.FindControl("HiddenField1");
var j = test.Value;
}
Try:
HiddenField colname = (HiddenField)Page.FindControl("The id of control");
private void GetParentPageHiddenField()
{
System.Web.UI.WebControls.HiddenField ParenthiddenField = null;
Control ctl = this.Parent;
while (true)
{
ParenthiddenField = (System.Web.UI.WebControls.HiddenField)ctl.FindControl("ParentPageHiddenFieldID");
if (ParenthiddenField == null)
{
if (ctl.Parent == null)
{
return;
}
ctl = ctl.Parent;
continue;
}
break;
}
var parentHiddenFieldValue=ParenthiddenField.Value;
}
I want to use getJSON()'s demo to show its use insetead of $.ajax.
I've till created the following code.
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Test_JSON.aspx.vb" Inherits="Test_HTML" %>
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test HTML</title>
<script src="Script/jquery-1.9.1.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
Enter Name:
<asp:TextBox runat="server" ID="txtName"></asp:TextBox>
<asp:Button runat="server" ID="btnView" Text="View Label of Name" />
</div>
</form>
<script type="text/javascript">
function getJsonData() {
debugger;
$("#btnView").val = $("#txtName").val();
var objJson = {};
objJson["name"] = $("#txtName").val();
return objJson;
}
$("#btnView").click(function(event) {
debugger;
$.getJSON('/Test_JSON.aspx/getJsonData', function(result) {
debugger;
$('<p> APPEND TEXT </p>').appendTo('#btnView');
$('<p> PREPEND TEXT </p>').prependTo('#btnView');
});
});
</script>
</body>
</html>
VB code for PageMethod
Imports Newtonsoft.Json
Partial Class Test_HTML
Inherits System.Web.UI.Page
<Web.Services.WebMethod()> _
Public Shared Function getJsonData(ByVal name As String) As String
Dim jsonString As String = String.Empty
Dim dt_jsonData As New DataTable
Dim dr As DataRow = dt_jsonData.NewRow
Try
dt_jsonData.Columns.Add("name")
dr("name") = name.ToString.Trim()
dt_jsonData.Rows.Add(dr)
If dt_jsonData.Rows.Count <> 0 Then
jsonString = JsonConvert.SerializeObject(dt_jsonData)
End If
Catch ex As Exception
Return ""
Exit Function
End Try
Return jsonString
End Function
End Class
I want to get data from getJsonData(). But my getJSON() is not getting executed with URL. Is there any other way I should use this?
All I need to do is:
1> Enter text in text box
2> Click on button
3> Get textbox's value through getJSON() method and use it somewhere else.
4> And also use appendTo and prependTo methods for demo.
How can I register AND execute that JavaScript function in ASP.NET on a Page_Load event so my textbox content gets validated and if nothing is in there I can disable a save button?
function Validate(source, arguments)
{
}
Use ClientScriptManager.RegisterStartupScript
See here for example
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
public void Page_Load(Object sender, EventArgs e)
{
// Define the name and type of the client scripts on the page.
String csname1 = "PopupScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
StringBuilder cstext1 = new StringBuilder();
cstext1.Append("<script type=text/javascript> alert('Hello World!') </");
cstext1.Append("script>");
cs.RegisterStartupScript(cstype, csname1, cstext1.ToString());
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>RegisterStartupScript</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
Hope this helps