How to include text inside div using HttpContext? - c#

I have included a div in my web page using HtmlGenericControl.
With a button click , i want to add text inside the div using HttpContext. I don't want to use InnerHtml because the browser hangs when the text i want to include is very long.
I tried the following way but it prints the text outside the div.
Please Help.
Thanks!
public partial class TextViewer : System.Web.UI.Page
{
public HttpContext ctx;
protected void Page_Load(object sender, EventArgs e)
{
HtmlGenericControl myDiv = new HtmlGenericControl("div");
myDiv.Style.Add(HtmlTextWriterStyle.BackgroundColor, "Blue");
this.Controls.Add(myDiv);
ctx = this.Context;
}
protected void Button1_Click(object sender, EventArgs e)
{
ctx.Response.Write("supposed to be printed inside myDiv.");
}
}

You can write to the HttpContext from code behind and access its value from jQuery.
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
HtmlGenericControl myDiv = new HtmlGenericControl("div");
myDiv.ID = "myDiv";
myDiv.Style.Add(HtmlTextWriterStyle.BackgroundColor, "Blue");
this.Controls.Add(myDiv);
}
protected void Button1_Click(object sender, EventArgs e)
{
HttpContext.Current.Application["MyData"] = "Supposed to be printed inside myDiv.";
}
.ASPX:
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var data = '<%= HttpContext.Current.Application["MyData"] != null ? HttpContext.Current.Application["MyData"].ToString() : "" %>';
$("#myDiv").append(data);
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
</body>

In such case, you can split your text into many spans and set each span's text separately
foreach(var paragraph in myText)
{
var span = new HtmlGenericControl("span");
span.InnerHtml = paragraph;
myDiv.Controls.Add(span);
}

Related

Why I get error when I try to use variable of form class from designer?

In code behind I have property called ReportFeatures and Page_Load event:
public partial class FeatureList : System.Web.UI.Page
{
protected string ReportFeatures;
protected void Page_Load(object sender, EventArgs e)
{
IEnumerable<ReportFeature> featureProps = fim.getFeatureProperties();
ReportFeatures = featureProps.ToJson();
}
}
In designer I tried to access ReportFeatures variable:
<head runat="server">
<title></title>
<script type="text/javascript">
window.reportFeatures = <%= ReportFeatures%>;
</script>
</head>
When page loaded I get this error:
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
Any idea why I get that error, and how to fix it?
Instead of using <%= ... %> block, try using data binding expression syntax (<%# ... %>), because <%= ... %> implicitly calls Response.Write() method in Page.Header which counts as code block while data binding expression doesn't count:
<head runat="server">
<title></title>
<script type="text/javascript">
window.reportFeatures = <%# ReportFeatures %>;
</script>
</head>
Then add Page.Header.DataBind() method in Page_Load event, because you want to bind ReportFeatures inside <head> tag which contains runat="server" attribute:
protected void Page_Load(object sender, EventArgs e)
{
IEnumerable<ReportFeature> featureProps = fim.getFeatureProperties();
ReportFeatures = featureProps.ToJson();
// add this line
Page.Header.DataBind();
}
More details about this issue can be found here.

Calling a javascript method from the code behind

I need to call a JavaScript method with parameters from the code behind.
Javascript method
<script type="text/javascript">
function changeControlSample(path)
{
$find('<%= PartialUpdatePanel7.ClientID %>').set_UserControlPath(path);
$find('<%= PartialUpdatePanel7.ClientID %>').refresh();
}
</script>
<iucon:PartialUpdatePanel runat="server" ID="PartialUpdatePanel7"
DisplayLoadingAfter="500" InitialRenderBehaviour="Clientside" EncryptUserControlPath="false">
<LoadingTemplate>
<div style="margin-left: 84px; margin-top: 10px;">
<asp:Image ID="Image1" runat="server" ImageUrl="~/images/loading.gif" />
</div>
<div style="text-align: center">
Updating...
</div>
</LoadingTemplate>
</iucon:PartialUpdatePanel>
The code Behind of the page
protected Consultation controlconsultation = new Consultation();
protected void Page_Load(object sender, EventArgs e)
{
PartialUpdatePanel7.UserControlPath = "Espace_Candidat/Consultation.ascx";
controlconsultation.imageinfo += controlconsultation_imageinfo;
Session["controlconsultation"] = controlconsultation;
}
void controlconsultation_imageinfo(object sender, CommandEventArgs e)
{
PartialUpdatePanel7.UserControlPath = "Espace_Candidat/InfoEdition.ascx";
Page.ClientScript.RegisterStartupScript(this.GetType(),
"CallMyFunction",
"changeControlSample('Espace_Candidat/InfoEdition.ascx')", true);
}
Code behind of the user control
public event CommandEventHandler imageinfo ;
protected void Page_Load(object sender, EventArgs e)
{
Consultation current = (Consultation)Session["controlconsultation"];
imageinfo = current.imageinfo;
}
protected void Valider (object sender, CommandEventArgs e)
{
if (imageinfo != null)
{
string pageNumber = (string)e.CommandArgument;
CommandEventArgs args = new CommandEventArgs("Control", pageNumber);
imageinfo(this, args);
}
}
This call didn't work even I change the JavaScript method by another one.
For example, if I try
Page.ClientScript.RegisterStartupScript
(this.GetType(),
"CallMyFunction",
"alert('blabla');",
true);
I got the same result.
So, What is the error that I commited?
How can I fix my code?
If you have update panel in page then call like this,
ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), Guid.NewGuid().ToString(), #"<script type='text/javascript'>changeControlSample('" + path + "');</script>", false);
It don't have update panel then call like this
Page.ClientScript.RegisterStartupScript(this.GetType(), "tabselect", "<script type='text/javascript'>changeControlSample("' + path + '");</script>");
If you wish to call JavaScript method with parameters from the code behind you can get this done using
ClientScriptManager.RegisterStartupScript Method
please check the link given below:
http://msdn.microsoft.com/en-us/library/z9h4dk8y(v=vs.110).aspx
Hope this helps.

Access the Label value on Page load in c# when value set through jQuery

I am posting this question again, maybe this time more accurate description.
The problem is , I am using jQuery to set the Label's text value and it works fine on browser, but when I want to save it to string, it does not save it. Here is the
front End Html Code.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(window).load(function () {
var myNewName = "Ronaldo";
$('#<%= Label1.ClientID %>').text(myNewName);
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>
</body>
</html>
And here is the Back End C# Code On Page Load
using System;
using System.Web.UI;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
string mynameCheck = Label1.Text;
if (mynameCheck=="Ronaldo")
{
Response.Write("Yes Name is Fine");
}
else
{
Response.Write("Name's not Fine");
}
}
}
The result displayed is
Name's not Fine
Ronaldo
Seems like the string is still Null. Is there any problem of rendering??
label is not input type so you can not get changed values through jquery on server side. You can use hidden field for this purpose.
Your server side code (c#) can not access the form data until your client side code (HTML/Javascript) posts it.
Why do you want to the name already at the PageLoad event?
You could add a asp:Button with an attached onClick event handler to read the value of your asp:Label.
Labels do not maintain viewstate. The server will not post that information back to the server. You can try explicitly enabling the ViewState on your Label, but if that doesn't work, you will have to store that value in a hidden field.
First Call Page Load event and after that call JQuery Window.Load event.
So if you want to set any content in Label then you can do using onClientClick of button.
For ex.
<asp:Button ID="btn" runat="server" Text="Click me" OnClientClick="SetClientValues();" />
<script type="text/javascript">
function SetClientValues() {
var myNewName = "Ronaldo";
$('#<%= Label1.ClientID %>').text(myNewName);
}
</script>
At server side button event you can get Label values that sets at client side.
protected void btn_Click(object sender, EventArgs e)
{
string mynameCheck = Label1.Text;
if (mynameCheck=="Ronaldo")
{
Response.Write("Yes Name is Fine");
}
else
{
Response.Write("Name's not Fine");
}
}
It will print Yes Name is Fine
This should do it:
<script type="text/javascript">
$(window).load(function () {
if($('#<%= Txt1.ClientID %>').val() != "Ronaldo"){
var myNewName = "Ronaldo";
$('#<%= Txt1.ClientID %>').val(myNewName);
$('#<%= Label1.ClientID %>').text(myNewName);
$('#<%= Btn1.ClientID %>').click();
}
});
</script>
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:TextBox ID="Txt1" runat="server" style="display:none"></asp:Label>
<asp:Button ID="Btn1" runat="server" style="display:none" Click="Btn1_Click"></asp:Label>
</form>
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
Label1.Text=Txt1.Text;
string mynameCheck = Label1.Text;
if (mynameCheck=="Ronaldo")
{
Response.Write("Yes Name is Fine");
}
else
{
Response.Write("Name's not Fine");
}
}
}
protected void Btn1_Click(object sender, EventArgs e)
{ }
Hope it helps :)

How to enable javascript in asp.net webforms

i am trying to use javascript events in asp.net webforms. but events for input controls like textfield, such as onClick, onFocus,onBlur, dont appear. do i need to change my directive:
<%# Page Title="" Language="C#" MasterPageFile="~/YourGuruMaster.master" AutoEventWireup="true" CodeFile="AskQuestion.aspx.cs" Inherits="AskQuestion" %>
i want to be able to do this:
//code page
protected void Page_Load(object sender, EventArgs e)
{
QuestionTextBox1.Attributes["onfocus"] = "ClearSearchText()";
//Markup page
function ClearSearchText() {
var searchUserName = document.getElementById('<%=QuestionTextBox1.ClientID%>');
if (searchUserName.value = searchUserName.defaultValue) {
searchUserName.value = "";
}
return false;
}
<p dir="rtl" style="">
<asp:TextBox ID="QuestionTextBox1" runat="server" Width="702px"
Text="פרטים עד 5000 תווים"></asp:TextBox>
Add onfocus and onblur into the markup as follows:
<asp:TextBox ID="TextBox1" runat="server" onfocus="TextBox1_focus(this, event)" onblur="TextBox1_blur(this, event)" Text="Search..."></asp:TextBox>
<script type="text/javascript">
var searchText = 'Search...';
function TextBox1_focus(sender, e) {
if (sender.value == searchText)
sender.value = '';
}
function TextBox1_blur(sender, e) {
if (sender.value == '')
sender.value = searchText;
}
</script>
Well, not sure which ASP.NET version you use. I think last versions allow this (rendering attributes that the server controls don't understand to the browser still). Try using "onfocus" instead (lower case).
However, if this is not working for you, then you have to do it from code behind...
protected void Page_Load(object sender, EventArgs e)
{
QuestionTextBox1. Attributes["onfocus"]="someJavaScriptMethod";
}
Alternatively, if you have jQuery in the page you can go something like ...
<script type="text/javascript">
$(function() {
$('#<%= QuestionTextBox1.ClientID %>').focus(someJavaScriptMethod);
});
</script>
If you do that, inside someJavaScriptMethod(), you can use the word this to point at the focused control, and you can create a jQuery object from it easily like $(this).
.
Please leave me a comment if none of the above solves your problem.

Trigger for UpdatePanel disappearing when added to a "custom control"

Basically, in a nutshell, the problem is that dynamically generated triggers for an UpdatePanel can no longer be found (by ASP.NET) as soon as I add them as children of a custom control.
Since the amount of code I'm working on is quite substantial I've recreated the problem on a smaller scale, which will make it easier to debug.
The error thrown in my face is:
A control with ID 'theTrigger' could not be found for the trigger in UpdatePanel 'updatePanel'.
I'm not sure whether this implementation of a "custom control" is the right way to go about it, but I did not write the original implementation: I'm working with code written by a previous developer to which I cannot make large modifications. It looks a little unusual to me, but, alas, this is what I've been given.
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestWeb.Default" %>
<!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:Panel runat="server" ID="panel">
</asp:Panel>
<asp:ScriptManager ID="scriptManager" runat="server"></asp:ScriptManager>
<asp:UpdatePanel runat="server" ID="updatePanel" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblSomething" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace TestWeb
{
public partial class Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
UselessTableWrapper table = new UselessTableWrapper();
TableRow tr = new TableRow();
TableCell td = new TableCell();
LinkButton button1 = new LinkButton { ID = "theTrigger", Text = "Click Me" };
button1.Click += button1_Click;
td.Controls.Add(button1);
tr.Controls.Add(td);
table.AddRow(tr);
panel.Controls.Add(table);
// ### uncomment these lines (and comment the one above) to see it working
// ### without the custom control
/*
Table realTable = new Table();
realTable.Controls.Add(tr);
panel.Controls.Add(realTable);
*/
updatePanel.Triggers.Add(new AsyncPostBackTrigger { ControlID = "theTrigger", EventName = "Click" });
scriptManager.RegisterAsyncPostBackControl(button1);
}
protected void button1_Click(object sender, EventArgs e)
{
lblSomething.Text = "Random number: " + new Random().Next(100);
updatePanel.Update();
}
}
}
MyControl.cs
using System;
using System.Web.UI.WebControls;
namespace TestWeb
{
public class UselessTableWrapper : WebControl
{
private Table table = new Table();
protected override void OnPreRender(EventArgs e)
{
Controls.Add(table);
}
public void AddRow(TableRow row)
{
table.Controls.Add(row);
}
}
}
Any ideas would be greatly appreciated.
Edit
I've tried switching the OnPreRender event for this (found in a tutorial):
protected override void RenderContents(HtmlTextWriter writer)
{
writer.BeginRender();
table.RenderControl(writer);
writer.EndRender();
base.RenderContents(writer);
}
... hoping that it would fix it, but it does not.
this is the approach that I've taken with loading a ascx web control inside an aspx control from the code behind.
In the control:
namespace dk_admin_site.Calculations
{
public partial class AssignedFieldCalculation : System.Web.UI.UserControl
{
public static AssignedFieldCalculation LoadControl(Calculation initialData)
{
var myControl = (AssignedFieldCalculation) ((Page) HttpContext.Current.Handler).LoadControl(#"~\\Calculations\AssignedFieldCalculation.ascx");
myControl._initialData = initialData;
return myControl;
}
private Calculation _initialData;
public Calculation Data { get { return _initialData; } }
protected void Page_Load(object sender, EventArgs e) {}
}
}
in the web form code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
if (ScriptManager1.AsyncPostBackSourceElementID.StartsWith("ctl00$MainContent$calc") && ScriptManager1.AsyncPostBackSourceElementID.EndsWith("$btnRemoveCalculationFromField"))
{
//do something on the postback
}
else if (ScriptManager1.AsyncPostBackSourceElementID.StartsWith("ctl00$MainContent$calc") && (ScriptManager1.AsyncPostBackSourceElementID.EndsWith("$btnMoveCalculationUp") || ScriptManager1.AsyncPostBackSourceElementID.EndsWith("$btnMoveCalculationDown")))
{
//do something on the postback
}
}
foreach (Calculation calc in calculationCollection)
{
AssignedFieldCalculation asCalc = AssignedFieldCalculation.LoadControl(calc);
asCalc.ID = "calc" + calc.UniqueXKey;
pnlFieldCalculations.Controls.Add(asCalc);
foreach (Control ct in asCalc.Controls)
{
if (ct.ID == "btnMoveCalculationDown" || ct.ID == "btnMoveCalculationUp" || ct.ID == "btnRemoveCalculationFromField")
{
ScriptManager1.RegisterAsyncPostBackControl(ct);
}
}
}
}
A few things to note:
You need to make each control ID unique when adding it to the asp:Panel (called pnlFieldCalculations).
The LoadControl method allows you to pass initial arguments

Categories

Resources