How can I use C# methods to alter an Asp:TextBox item's Text value(or any other value) dynamically only from ASPX side?
I can access any C# variable using <%= .... %> to select a class for a div. But cannot use it for any Aspx item's Text property.
Here, the three aspx items fail to fetch the variable from C# part but divs are easily using that for selecting a CSS class
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="test.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<link href="site.css" rel="stylesheet" />
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="testBox" runat="server" Text="<%= test.TestClass.TestMethod() %>"></asp:TextBox>
bye bye world!
</div>
<div>
<asp:TextBox ID="TextBox2" runat="server" Text='<%= test.TestClass.TestMethod() %>'></asp:TextBox>
bye bye world!
</div>
<div class="<%=test.TestClass.CustomCSSClass() %>" >hello world! </div>
<div class='<%=test.TestClass.CustomCSSClass() %>' >hello world! </div>
<div class=<%=test.TestClass.CustomCSSClass() %> >hello world! </div>
</form>
</body>
</html>
Output is:
As you can see, only divs are accepting <%= ... %> and they are styled. But Asp:TextBox items having issues and printing the C# code directly instead of the value.
Here is the CSS(not related but putting anyway):
body {
}
.CustomCSSClass {
margin-top:50px;width:300px;height:200px;background-color:red;
}
Here is the C# methods that Im testing:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace test
{
public class TestClass
{
public static string TestMethod()
{
return "ASPX and HTML and CSS";
}
public static string CustomCSSClass()
{
return "CustomCSSClass";
}
}
}
While double-quote, single-quote and even quoteless versions work for selecting a style class, aspx fails to compile for quoteless version and other two are giving wrong results.
The <%= ... %> bee stings are short hand for calling Response.Write(). In other words, their result goes directly to the output stream written to the browser. You can't assign it to the property of an ASP.Net control. ASP.Net controls are server-side controls, meaning they have properties that are processed by the server before html is generated and later written to the response stream. The two items work at different levels of abstraction, and don't really fit well together.
If you want to set the text property of a control, do it in a code-behind file, or in a server-side method in your same file. If you don't want to have a code-behind file or server-side methods, then you don't need server-controls and can just use an html input element instead.
Related
I'm here learning ASP.NET which is why I'm obviously here asking a question. So when I run a statement inside of <% %> delimiters everything works fine. I try to instead run it in a <script runat="server"> and it doesn't work. I'm just curious to what is so significant different between the two methods. I am suppose to be using the script method, but it only works with the <% %>.
My example is this... basic standard form getting "userInput" (a number) from the POST method.
<form action="calcprime.aspx" method="post">
Enter a number between 1-999:
<input type="text" name="userInput" maxlength="3" />
<input type="submit" name="submit" value="Submit" />
</form>
Then if I need to convert the string into an integer to do math on it I would do this...
<%# Page Language="C#" %>
<script runat="server">
int num = int.Parse(Request.Form["userInput"]);
</script>
<%=num%> // <-should display the number in theory..(in my head)
Unfortunately the above code errors and does not work for me, However the alternative using only <% %> using the same exact method of code works 100% fine. Such as below...
<%# Page Language="C#" %>
<%
int num = int.Parse(Request.Form["userInput"]);
Response.Write(num); //displays the number as it should.. 100% working
%>
So my question is. Why doesn't the script way work? Isn't it the same thing? What is the correct way to handle this basic scenario in ASP.NET using C#? Is my approach even practical, or is there a standard that I should be aware of? The number will have math done to it, which is why I need it converted to an integer. This is just a somewhat basic foundational stuff here that I feel I should know the correct way to go about it before learning bad practices.
<script runat="server">
int num = 1;
</script>
<%=num%>
That works fine on my machine. I see the 1 on my page.
However, this doesn't work:
<script runat="server">
int num = int.Parse(Request.Form["userInput"]);
</script>
<%=num%>
I get this error:
CS0120: An object reference is required for the non-static field,
method, or property 'System.Web.UI.Page.Request.get'
I suspect you got that error too, but didn't include it in your question. NOTE if you get an error in your code, include it in your question. Don't assume we know you got an error.
This works, assuming I add query string appropriately to the request URL:
<script runat="server">
int num = int.Parse(HttpContext.Current.Request.QueryString["randomnum"].ToString());
</script>
<%=num%>
I suspect this will work too, assuming you've already posted form values to the page. However, your question was not complete, so I don't know if you did it or not. That just goes to show, you need to submit a Minimal, Verifiable, and Complete example.
<script runat="server">
int num = int.Parse(HttpContext.Current.Request.Form["userInput"]);
</script>
<%=num%>
In the end however, you probably shouldn't be doing code blocks inline (whether using a script tag or inline expression) on your page. That's better handled on code behind. <% %> stuff is fine in some contexts, but you should usually only use it to inject a value onto the page, for example when you're eval'ing something in a repeater. And if you find yourself doing a lot of those inline expressions, you might consider switching to ASP.NET MVC or Web Pages. Both of those use the Razor view engine, which is much cleaner.
Your .aspx files are converted into .cs files (i.e. pure C#) by the behind-the-scenes ASP.NET compiler (separate from the C# compiler in the IDE). You can see these temporary .cs files if you locate your "Temporary ASP.NET Files" folder on your computer.
The class in these .cs files has a big function called Render which is what outputs to the response stream (using Response.Write). All of the static HTML in your .aspx file is converted into a String instance and fed directly into Response.Write.
<% %> blocks are converted into inline C# code that breaks-up these massive String instances inside the Render function.
<script runat="server"> blocks are instead pasted as class members in this runtime-generated class.
<asp:Foo runat="server"> elements are converted into Control instantiation and render calls.
So this:
<%# Page Inherits="ParentPageClass" %>
<html>
<head>
<script runat="server">
String DoSomething() {
return "lulz";
}
</script>
</head>
<body>
<% int x = 5; %>
<%= x %>
<div>
<asp:Button runat="server" />
</div>
</body>
</html>
Is converted into this:
(I have simplified this example by removing the extra tracing calls. The #line text are special preprocessor instructions so the YSOD system can map runtime errors back to your .aspx file).
namespace ASP {
[System.Runtime.CompilerServices.CompilerGlobalScopeAttribute()]
public class webform1_aspx : ParentPageClass, System.Web.SessionState.IRequiresSessionState, System.Web.IHttpHandler {
String DoSomething() {
return "lulz";
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
private global::System.Web.UI.WebControls.HyperLink #__BuildControl__control2() {
global::System.Web.UI.WebControls.HyperLink #__ctrl;
#__ctrl = new global::System.Web.UI.WebControls.HyperLink();
#__ctrl.ApplyStyleSheetSkin(this);
#__ctrl.Text = "WebControls are evil";
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
private void #__BuildControlTree(webform1_aspx #__ctrl) {
this.InitializeCulture();
global::System.Web.UI.WebControls.HyperLink #__ctrl1;
#__ctrl1 = this.#__BuildControl__control2();
System.Web.UI.IParserAccessor #__parser = ((System.Web.UI.IParserAccessor)(#__ctrl));
#__parser.AddParsedSubObject(#__ctrl1);
#__ctrl.SetRenderMethodDelegate(new System.Web.UI.RenderMethod(this.#__Render__control1));
}
private void #__Render__control1(System.Web.UI.HtmlTextWriter #__w, System.Web.UI.Control parameterContainer) {
#__w.Write("\r\n </head>\r\n <body>\r\n ");
#line 11 "c:\users\dai\documents\visual studio 2013\Projects\WebApplication1\WebApplication1\WebForm1.aspx"
int x = 5;
#line default
#line hidden
#line 12 "c:\users\dai\documents\visual studio 2013\Projects\WebApplication1\WebApplication1\WebForm1.aspx"
#__w.Write( x );
#line default
#line hidden
#__w.Write("\r\n <div>\r\n ");
parameterContainer.Controls[0].RenderControl(#__w);
#__w.Write("\r\n </div>\r\n </body>\r\n </html>");
}
}
}
I have a function that generates a javascript code for me.
<img src="abc.png" alt="hello" onclick="<%: getOnCilckJS(arg) %>" />
c# code
protected String getOnCilckJS(int arg)
{
if (arg==1)
{
return "alert('hello world');";
}
else
{ return "alert('hello universe');";
}
}
all works fine apart from when the page is loaded asp.net converts single quotations ' to the encoded html string (')
How can I avoid this and make ' appear in the html?
Your application is Web Forms or MVC?
If it is MVC, you can try the Html.Raw(...) function, If it is Web Forms you can check this link.
You're using <%: %>, which actually does encode the value. You're looking for <%= %>.
See also Diference between special tags asp.net.
In ASP.NET WebForms the razor syntax is invalid so the way to stop the string encoding in the output of a string is to use the HtmlString() for example the inline syntax is:
<%: new HtmlString(stringVariable) %>
Below is an example how to output a variable in JavaScript inline code on a ASP.NET WebForm page. The code sample outputs a C# string array into a JavaScript array:
<script type="text/javascript">
var array = ["<%: new HtmlString(string.Join(#""",""", stringArray)) %>"];
</script>
Normally, the double quote characters are html encoded and converted as " and breaks the JavaScript syntax - using the HtmlString() method stops the encoding.
However, as stated in previous answer to avoid using the HtmlString() simply use the appropriate special ASP.Net tag syntax to output your values - <%: %> encodes characters and <%= %> is raw output!
Review the differences between ASP.Net special tags here!
Your code working to me :
But just change <%: to <%= ( and I send the parameter myself)
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="xxxx.aspx.cs" Inherits="SampleAngularApp.xxxx" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
**<img src="abc.png" alt="hello" onclick="<%= getOnCilckJS(11) %>" />**
</div>
</form>
</body>
</html>
Server side
**protected string getOnCilckJS(int arg)**
{
if (arg == 1)
{
return "alert('hello world');";
}
else
{
return "alert('hello universe');";
}
}
I got the alert message without any single quote
I'm trying to use CKEditor in my Webforms application and I have tried many other methods without success. Can someone help? The site uses a Site.Master file which all the aspx files provide content for using content place-holders. So I place the JavaScript call in the ASPX rather than in the master file.
I'm also trying to get it to edit in a content editable div element. It works fine in a small test site but not in my application. Any ideas?
My Site.master has two content placeholders I want to use:
<asp:ContentPlaceHolder ID="Scripts" runat="server" />
and
<asp:ContentPlaceHolder ID="MainContent" runat="server">
An then my aspx files have:
<asp:Content ID="Content3" ContentPlaceHolderID="Scripts" runat="server">
<script src="ckeditor/ckeditor.js"></script>
</asp:Content>`
and
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div id="renderTarget" renderwidth="1100">
</asp:Content>
</asp:Content>
Somewhere in my JavaScript, I set the content editable of my renderTarget div to true.
$(".contentbox[dynamic='true']").attr("contenteditable", "true");
And at this point, I expect CKedtor to add its controls to the div. But It doesn't. i use the same process with TinyMCE and it works fine.
If you have CKEditor in your project correctly, it is as simple as:
<textarea cols="80" class="ckeditor" id="editor1" name="editor1" rows="10"></textarea>
or even
<div contenteditable="true">...</div>
Also, you may want to read up on jQuery Selectors.
An example more like what you posted:
<div id="ckMe">...</div>
<script>
$(document).ready(function () {
$("#ckMe").attr("contenteditable", "true");
});
</script>
all you need is to install the version for asp.net in your project and then just use it as simple as adding a usercontrol:
<ckeditor:ckeditorcontrol ID="CkEditor1" runat="server"></ckeditor:ckeditorcontrol>
Documentation from ckEditor
How can I display an html textbox with value obtained from code behinh?
As long as your string value is not private, you should be able to do something like this
<input type="text" value="<%= YourStringValue %>" />
You could use an actual <asp:Textbox /> and set it's "text" value directly from the code behind. If you want to directly inject text into a "normal" html textbox (or anywhere else for that matter), you can use <%= SomeValue %>. Yet another way is to include the "runat=server" attribute on standard html elements, allowing you to manipulate them from the codebehind.
Normally I'd just go for the built-in ASP textbox control so I don't have to worry about persisting values/wiring up viewstate/etc. Injecting dynamic content into plain html elements tends to be an edge case requirement...
<%# 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">
protected void Page_Load(object sender, EventArgs e)
{
//assign text value here
txt1.Value = "hello world!";
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="txt1" runat="server" type="text" />
</div>
</form>
</body>
</html>
I've got a master page setup with a contentplaceholder control inside the title tag as so:
<head id="head1" runat="server">
<style type="text/css">
body { font-family: Tahoma; font-size: 9pt; }
</style>
<title><asp:contentplaceholder id="title" runat="server" /></title>
</head>
That contentplaceholder is implemented inside a page that uses that masterpage as so:
<asp:content runat="server" contentplaceholderid="title">
Welcome: <%= this.BasketID %>
</asp:content>
I'm trying to then get a copy of the substituted title inside the masterpage body (also tried inside the page - and this doesnt work either) like:
<p>
<strong>Subject:</strong> <%# Page.Title %>
</p>
In all cases Page.Title and Page.Header.Title are "" (I've tried both databinding and using the <%= %> syntax to no avail.
Does anyone know what is going on here and how I can overcome this?
Thanks.
The problem you're getting is because you are 'tricking' the page cycle. You'd better use this in the codebehind of the page:
Master.Title = "Welcome: " + basketId
You could do it this way however; on the masterpage: create a HtmlTextWriter, configure it to write to a MemoryStream. Render the 'title' contentplaceholder to the HtmlTextWriter, attach a StreamReader to the stream to grab the content as a string, and output this to your page. Yet, this is not efficient, and way too much work :-)