I want to add a hidden field programmatically to an asp.net page, read and change it via javascript. So far my code fails at reading the added hidden field.
Here is a simple example:
Default.aspx:
<!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" >
<body>
<input type="hidden" id="myHiddenField1" value="blub" runat="server" />
<button onclick="myFunction()">click me</button>
<script>
function myFunction() {
var testVar = document.getElementById("myHiddenField1").value; //works: field defined in aspx page
var testVar2 = document.getElementById("myHiddenField2").value; //fails, Object required: field defined in codebehind
alert(testVar);
}
</script>
</body>
</html>
Default.aspx.cs (includes ommited):
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Page.RegisterHiddenField( "myHiddenField2", "bla!" ); doesnt work either
Page.ClientScript.RegisterHiddenField( "myHiddenField2", "bla" );
}
}
[edit]
The error i receive is: Microsoft JScript runtime error: Object required. If i add an alert(testVar2) and ignore the error the message box displays "undefined".
[/edit]
[edit2]
[removed edit, since i was wrong]
[/edit2]
Summering up my question: How do i create a hidden field in codebehind so i can get and set it from javascript?
You could try something like this:
protected void Page_Load(object sender, EventArgs e)
{
HtmlInputHidden hidden2 = new HtmlInputHidden();
hidden2.ID = "Here you will put the id of the control";
hidden2.Value = "Here you will put your value";
this.Controls.Add(hidden2);
}
At the top of your source code file, you have to add this statement:
using System.Web.UI.HtmlControls;
The main problem was that the following line was missing in the aspx page:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
The codebehind was never executed.
Related
I have an ASP.net WebForm. The markup is like:
<div>
<input type="text" id="input" runat="server" value=" " />
<asp:Button Text="send" OnClick="btnsend_Click" ID="btnsend" runat="server" />
</div>
This HTML is generated at runtime . The events are defined in the code behind file.
I need to add these controls at runtime. I tried to use the Literal-Control but the controls are working just like HTML Controls and not like ASP.net Controls.
EDIT:
Note: The Project type should be Website, not a web Application. Web application won't support on demand compilation where website yes, it is.
If I understood currectly, you want to take the Markup from User which contains even asp.net controls and scriplets too.
if this is the case, Follow below steps:
Create a dummy .ascx control file, like DynamicMarkup.ascx with empty content
Add this user control to the page (xxxx.aspx) where you want to show this control statically so it registered to the page
<%# Register src="~/DynamicMarkup.ascx"
tagname="DynamicMarkup" tagprefix="MyASP" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder runat="server"
ID="DynamicMarkupContainer" ></asp:PlaceHolder>
</div>
</form>
</body>
</html>
Write user input markup (may be get from database based on your criteria) to the DynamicMarkup.ascx file in page OnInit of the page (xxxx.aspx) And the create object of this DynamicMarkup
DynamicMarkup dynamicMarkup = LoadControl("~/DynamicMarkup.ascx") as
DynamicMarkup;
DynamicMarkupContainer.Controls.Add(ucSimpleControl);
I have not tested this approach, Just give a thought, With this you may get some session overwriting issue which you need handle.
Hope this will help!!
OLD:
is this the one that you are expecting? TextBox, and Button controls are available in System.Web.UI.WebControls namespace.
void Page_Load(Object sender, EventArgs e)
{
TextBox input = new TextBox();
input.Id ="input";
this.PlaceHolder.Controls.Add(input);
Button btnSend=new Button();
btnSend.Id ="btnSend";
btnSend.Text="Send";
btnSend.Click += new EventHandler(btnSend_Click);
this.PlaceHolder.Controls.Add(btnSend);
}
void btnSend_Click(object sender, EventArgs e)
{
// throw new NotImplementedException();
}
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!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">
<asp:PlaceHolder ID="phHolder" runat="server"></asp:PlaceHolder>
</form>
</body>
</html>
code behind :
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Init()
{
GenerateContorls();
}
protected void Page_Load(object sender, EventArgs e)
{
}
private void GenerateContorls()
{
TextBox newTxt = new TextBox() { ID = "txtsend" };
Button newBtn = new Button() { Text = "Send", ID = "btnsend" };
newBtn.Click += btnsend_Click;
phHolder.Controls.Add(newTxt);
phHolder.Controls.Add(newBtn);
}
protected void btnsend_Click(object sender, EventArgs e)
{
TextBox txt = (TextBox)this.FindControl("txtsend");
//your code
}
}
hope it helps
I am getting the System.String[] Error when trying to post data from a form below is my sample code.
Default.aspx:
<%# 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>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox id="AccidentDetailsDate" runat="server" />
<br /><br />
<asp:Button ID="Button1" Text="Submit" runat="server" />
</div>
</form>
</body>
</html>
Default.aspx.cs:
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
public void Page_Load(object sender, EventArgs e)
{
var AccidentDate = Request.Form.GetValues("AccidentDetailsDate");
Response.Write(AccidentDate);
}
}
If anyone could help me over this hurdle it would be much appreciated, I have spent the last 3 hour trying to resolve it!
In the page_load event try the following:
var AccidentDate = this.AccidentDetailsDate.Text;
Response.Write(AccidentDate);
Since AccidentDetailsDate is a text box you can access it in the code behind using the above syntax.
That's right, because you are getting array back, of all form elements named "AccidentDetailsDate".
Sounds like you want a single value:
var AccidentDate = Request.Form["AccidentDetailsDate"];
Response.Write(AccidentDate);
You are getting the error because of line:
Response.Write(AccidentDate);
Since your AccidentDate is a string[], where as Response.Write expects a single string value.
The problem is because of the earlier line, you are using Request.Form.GetValues, which would return an array of string, You don't have to use Request.Form, since your TextBox is already marked as runat="server", you can simply do:
var AccidentDate = AccidentDetailsDate.Text;
So your code should be:
public void Page_Load(object sender, EventArgs e)
{
var AccidentDate = AccidentDetailsDate.Text;
Response.Write(AccidentDate);
}
From the name of the control it appears that you are trying to get DateTime from user, you should parse it to DateTime in .Net framework or use a DateTimePicker
Try adding ToString() like this.
var AccidentDate = Request.Form.GetValues("AccidentDetailsDate").ToString();
Response.Write(AccidentDate);
I want to get HTML DIV content via asp.net C# code behind event.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Report.aspx.cs" Inherits="WebApplication1.Report.Report" %>
<!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>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function () {
$('#_Hidden_CrystalReportContent').hide();
$('#_Hidden_CrystalReportContent').html("<b>I want to get Current value. 1<sup>st</sup></b>");
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="_Hidden_CrystalReportContent">I want to get Current value.</div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</form>
</body>
</html>
My code behind file as below.
public partial class Report : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{}
protected void Button1_Click(object sender, EventArgs e)
{
string s = Request["_Hidden_CrystalReportContent"].ToString();
}
}
But I still cannot get div content value.
Please let me get your suggestion.
Make the div runat="server" to access on server.
Html
<div id="_Hidden_CrystalReportContent" runat="server">
Code behind
string htmlOfDiv = _Hidden_CrystalReportContent.innerHTML;
Javascript
$(document).ready(function () {
$('#<% _Hidden_CrystalReportContent.ClientID %>').hide();
$('#<%= _Hidden_CrystalReportContent.ClientID %>').html("<b>I want to get Current value. 1<sup>st</sup></b>");
});
Making a div server accessible by puttin runat="server" attribute cause the changed client id if CLientIDMode is not static. You will need to use ClientID attribute to get client id of div in javascript.
Edit: based on comments. You are trying to get the updated html, if so you then you wont get it as on post back only html form elements are posted. Put the changes in some hidden field and assess it on server.
In html
<input type="hidden" id="hdnDivContents" runat="server">
In javascript
$('#<% hdnDivContents.ClientID %>').val("<b>I want to get Current value. 1<sup>st</sup></b>");
In code behind
_Hidden_CrystalReportContent.innerHTML = hdnDivContents.Value;
I am trying to add a few additional lines of code to the Page_Load method of an ASP.Net page, where the existing Page_Load code is stored in a compiled codebehind DLL. I don't have access to the source for the DLL, although I can extract the code for the Page_Load method using Dis#.
What is the best way to add the new code? I need the existing Page_Load code to execute, together with the new code, and it doesn't matter in what order they execute.
Specifically, I'm fixing an old application that uses the Telerik RadEditor which doesn't work correctly under Firefox 6. See this page for the exact code I'm adding.
If you can access the ASPX portion, you can try adding a code block to the ASPX, and overriding OnInit or OnPreInit, which should work fine for the code you're trying to add.
<script runat="server">
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
if (Request.Browser.Browser.ToLowerInvariant() == "firefox")
{
System.Reflection.FieldInfo browserCheckedField = typeof(RadEditor).GetField("_browserCapabilitiesRetrieved", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
browserCheckedField.SetValue(RadEditor1, true);
System.Reflection.FieldInfo browserSupportedField = typeof(RadEditor).GetField("_isSupportedBrowser", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
browserSupportedField.SetValue(RadEditor1, true);
}
}
</script>
You can derive from the other Page class and add a Page.Load event handler:
public class YourPage : TheirPage
{
public YourPage() { Load += YourPage_Load; }
void YourPage_Load(object s, EventArgs e) { ... }
}
or even override OnLoad():
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
...
}
You would need to extract all source, add your code and rebuild the entire dll. There is not a way to do this without rebuilding the original assembly. This will be a problem if the original assembly is strong-named. Otherwise, it's a pain but you should be ok.
can you possibly hook into PreLoad in the aspx page? Controls are loaded at this point and you should be able to do what you need. Sometimes additional processing is required and you can hook into LoadComplete as well which I think may serve you best?
http://msdn.microsoft.com/en-us/library/system.web.ui.page.preload.aspx
http://msdn.microsoft.com/en-us/library/system.web.ui.page.onloadcomplete.aspx
If you can extract the code from the DLL by dissasembling it, you can disassociate the code behind the page and reimplement the logic in the markup.
<%# Page Language="C#" AutoEventWireup="true" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
lblTest.Text = "Something here";
}
</script>
<!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:Label ID="lblTest" runat="server" ></asp:Label>
</div>
</form>
</body>
</html>
You can derive from the existing class and override any of the rendering methods, such as the OnPreRender() method:
public class Class1 : _Default
{
protected override void OnPreRenderComplete(EventArgs e)
{
base.OnPreRenderComplete(e);
// add your code here
}
}
I have implemented master pages using this example How to implement a status bar in an ASP.NET application?. I have a property on my SiteMaster.cs inherited MasterPage called Environment. On my MasterPage.master I have this code:
<body>
<form id="frmMaster" runat="server">
<.. some content removed for brevity ...>
Environment: <%= this.Environment %>
</form>
</body>
What I would like to do is evaluate this.Environment and if it is "LIVE" then colour the background of this.Environment text red, and if it's "TEST" colour it yellow. How would I do this?
UPDATE I've just added this code to MasterPage.master
protected void Page_Load(object sender, EventArgs e)
{
lblEnvironment.Text = this.Environment;
if (this.Environment == "LIVE")
{
lblEnvironment.BackColor = System.Drawing.Color.Red;
}
}
The page loads, but the text does not get set, it's blank! Also the old text, that was populated is now blank too (I left the old code there for now). I also get a warning in Visual Studio:
'ASP.masterpage_master.Page_Load(object,
System.EventArgs)' hides inherited
member 'SiteMaster.Page_Load(object,
System.EventArgs)'. Use the new
keyword if hiding was intended.
UPDATE2: This is what I have in SiteMaster.cs
using System;
using System.Web.UI;
public class SiteMaster : MasterPage
{
public string StatusText { get; set; }
public string StatusTime { get; set; }
public string Environment { get; set; }
protected virtual void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
if (Session["status"] != null)
{
this.StatusText = Session["status"].ToString();
this.StatusTime = Session["statusTime"].ToString();
}
this.Environment = Session["environment"].ToString();
}
}
}
Instead of using the <%= syntax to print out the environment (this is using Response.Write), consider using a server control like a Literal or a Label. As you want to change the background colour, this suggests styling (CSS), so a Label would be appropriate.
(A Literal is just a text placeholder and renders no HTML, whereas a Label (usually) renders the text inside <span> tags.)
So I would change your master page markup to
Environment: <asp:Label ID="environmentLabel" runat="server" />
In the code-behind, set the Text property of environmentLabel to this.Environment. At the same time, test the value of the evironment, and set the BackColor property of the label as appropriate (or apply a CSS class).
UPDATE:
For a master page, you just need one class, which will inherit from System.Web.UI.MasterPage. If you create this in Visual Studio and call it SiteMaster, you'll get 3 files:
SiteMaster.Master (the markup)
SiteMaster.Master.cs (the code-behind)
SiteMaster.Master.designer.cs (automatically generated/updated)
In the SiteMaster.Master file, you'll want something like this:
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="SiteMaster.master.cs" Inherits="WebApplication1.SiteMaster" %>
<!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>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="environmentLabel" runat="server" />
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server" />
</div>
</form>
</body>
</html>
In SiteMaster.Master.cs, you'll need something like this:
using System;
namespace WebApplication1
{
public partial class SiteMaster : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
this.environmentLabel.Text = "environment";
this.environmentLabel.BackColor = System.Drawing.Color.Red;
}
}
}
As the environment label is on the master page, any normal page (ASPX) using this master page will get the label displayed. Every time a page is loaded, the Page_Load event in SiteMaster.Master.cs will be called, and the text will be updated. You don't need to define the MasterPage class yourself, that's provided by the .NET framework.
You may want to improve this Page_Load method, either by using ViewState and therefore only setting the text if you're not doing a PostBack, or by disabling ViewState on the environmentLabel control.
Finally, you'll have one or more ASPX pages in your site, with something like this at the top of the markup:
<%# Page Title="" Language="C#" MasterPageFile="~/SiteMaster.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
something like this..
var preTag = #" <font style=""background:yellow;color:#ff0000;font-weight:600;""><b>";
var postTag = " </b></font>";
Environment: <%= ((this.Environment=="LIVE") ? (preTag + this.Environment + postTag) : this.Environment) %>
You can also move the code from Page_Load to Page_PreRender in MasterPage.master and it should work.. it was blank because MasterPage.master Page_Load overwritten the Page_Load of SiteMaster.Master thus Environment was never assigned.