I am trying to use a checkbox that is dynamically declared in an .vb file that I am trying to write into my .aspx page. I am able to write a normal checkbox of <input type='checkbox /> from the .vb Class using Response.write, but it comes up blank when using <asp:Checkbox runat='server' />I need to pass whether or not the box is checked back to the server, because I am having to either approve something if one is checked, reject something if the other is checked or do nothing if neither are checked. I have figured out how to make them mutually exclusive either way so that is not the problem. Does anyone have any recommendations?
Your problem lies in the order that the pages are compiled in: When you place an asp control like the asp:checkbox, it is compiled into a regular checkbox with some javascript attached when it is sent over to the client.
When you write the string "<input type='checkbox />" to the page from the code-behind it is writing that string directly to the page, after the aspx page has compiled its controls, but since that is valid html the browser renders the control. When you write the asp:checkbox, the browser doesn't know what to do with it, because it is not valid html. In addition, the page has already been compiled, so there is no chance of .net creating the correct control for you.
You need to programmatic add the control to the webpage by creating a new control through the code behind
This site does a great job explaining it
And #toodles seems spot on. Writing static html and asp.net are two totally different ball games. I would spend a bit of time (like hours/days) reading/watching learning material to help you get on your feet.
The technical answers you are getting are all good. However, your question indicates that you really need to start by learning how asp.net server controls work. I suggest spending a couple hours watching the videos at http://asp.net and particularly http://www.asp.net/general/videos/intro-to-aspnet-controls
Then focus on understanding the page lifecycle and you'll have enough of the basics to be much more effective at asp.net. Have fun!
You can't use response.write to create server controls.
See this site for an example of the right way to do it:
http://msdn.microsoft.com/en-us/library/kyt0fzt1.aspx
Related
I'm newbie in ASP.NET and i think that my question is quite simple, but I'm not getting success in my searches through google or even stackoverflow.
I have a asp.net method (vb.net) that loads a entire html page inside a div.
Doing searches, i discovered that it can be like this:
On .aspx page:
<div id="content"></div>
On .vb codebehind:
Private sub LoadContent()
content.InnerHtml = MyDLL.LoadFromDatabase.Value.ToString()
End Sub
So, nothing special until here.
But, if consider that the html code loaded from database has form elements like <input id="name" type="text">, my problem starts...
On page postback these don't keep the values as <asp:TextBox> created natively on code, does.
And the other thing that I want is a way to retrieve the value from them to work on codebehind, like: myvar = content.Controls("name").Value
At least, is there a way to solve my problem?
Sorry for my bad english, and thanks so much.
CRice is right. If you want the viewstate to persist through postback you need to create the controls server-side.
Careful though: I've had bad experience with dynamically created controls on Asp.Net, specifically when trying to bind events to them. Not only would you have to use delegates and events (a hard topic for a newbie), also when I tried it a few years ago I just couldn't get it to work, no matter what.
If you're going for dynamic created controls, make sure it's worth the effort, because it WILL be an effort, now and in the future when you would like to maintain and add expand. A rule of thumb is that dynamic mechanisms are always harder to maintain than static ones, but they provide more flexibility.
Having that said, if you're still going for dynamic html loading, be aware that better solutions exist, though they require different architectures: client side frameworks (best is angluar.js) provide dynamic loading of "modules" (and much more), which is what you want. On the server side, asp.net MVC with its Razor view engine, partial views etc., is better suited for dynamic html generation.
Back to your original question,are you sure you need a full postback? What about a nice neat Ajax call to a web service? Can get the job done in many cases without reloading the whole page. I guess using jquery's $.ajax syntax and creating a simple .asmx web service will be easiest for you.
Last but not least, why use vb.net instead of c#? It sucks man. Give it up while you still can.
I am trying out with asp.net . One thing i was surprise is that in our design code we don't used general <html>,<body> etc. but we used <asp:content> , <asp:button> etc. well i tried to find it out why but ended upon the abstract msdn pages . So please help me on this one
Tags with <asp:... tag prefix means they are "server side controls", which means:
they are accessible to your program on the server side (events, parameters, etc.) and by client side script (e.g. JavaScript)
they will be "rendered" (output when running/"translated to") as standard HTML tags when you actually run your web site
As an example, while you are building your web page/s the tag <asp:textbox runat="server" id=foo... will output as <input type="text" id="foo when you run the ASP.net application in a browser.
You can create a simple web page, run it in a browser, then VIEW SOURCE to see this "translation" at work.
So while you are developing/designing your web application, ASP.Net will provide you with what they call "controls" (e.g. button controls, label controls, etc.). They will all be translated into standard HTML tags/elements at runtime.
The above relates to ASP.Net technology called "Web Forms".
You can start with it - its a bit easier to program against. When you get more advanced and/or prefer to do more "bare metal" standard HTTP POST/GET, then you can look into ASP.Net MVC/Razor - this ASP.Net architecture will let you use standard HTML and pretty much control everything (which also means you need to know how to control 'everything').
There's nothing wrong with using HTML tags in ASP.NET pages, as long as you use runat="server" on them of course. I like to use a bit of both, dependent upon what it is. I suppose a benefit of using HTML tags means that you become more comfortable with the HTML and do not depend on the ASP.NET syntax.
On the other hand, in some cases, it would be an incredibly laborious task to actually write ALL of the HTML in order to replicate a control. Something like a complex DataGrid with all the events would be an absolute nightmare to write the pure HTML/JavaScript for. Using the ASP.NET control & syntax makes it much quicker and cleaner in that scenario.
I've got an ASP.NET 3.5 Web Forms application in which a large chunk of code needs to be duplicated between a few different pages. Sounds like the ideal candidate for a user-control right? Problem is, this cannot be contained within a <form runat="server"> because it contains a client-side form of it's own.
There are no runat=server controls or postbacks or anything that really need that webform - think of it just as a chunk of HTML with a few basic <% %> tags. I'd just want to set a property on the control when it's loaded, so that it knows what to output. This is purely an exercise to make the code easier to maintain.
Before I resort to using an oldskool <!--#include-->, is there some better way of doing this?
You can still use a normal user control. Just don't rely on viewstate and postbacks and you shouldn't have any problems.
<%=Response.Write(File.ReadAllText(Server.MapPath("~/includes/filename.ext")))%>
Something along those lines, anyway.
Edit: Same functionality as a server side include, but if I'm not mistaken, enabling the SSI syntax requires an IIS change, where as this wouldn't.
Edit 2: I didn't see the note that your include contains asp.net code. This would obviously only work for client side code only. My mistake.
You can have as many form controls as you want but only one can have runat="server".
Some other techniques:
http://webproject.scottgu.com/CSharp/UserControls/UserControls.aspx
http://weblogs.asp.net/scottgu/archive/2005/08/28/423888.aspx
I'd still make it a control. The <% %> stuff could be labels/literals for more flexibility, and as soon as you get done saying there are no postbacks needed, you'll need them. Best to set up the other pages to include it as a control now for easier changes later. Heck - you could even take advantage control-level caching!
For example,
If I have a textbox with runat=server on a page, The value will be posted back to the server so I can access the properties in the code-behind.
However, under the following situations, does it still hold true?
A textbox with runat=server but does not appear in the function that is post back to. For example, a button is also on the page, when clicked a post back occurs and within the method that is raised, this textbox was not used.
Within a MasterPage, will a textbox residing on the Masterpage itself be posted back?
Because just thinking, isn't this mechanism bloated in nature?
If all input controls and its value are posted back on every single button click (even when the input control is not needed), doesn't this deteriorate performance?
Having just one Form Tag on the page really restricts us to using this mechanism?
Truly Understanding ViewState is a must read article on the subject of ASP.NET ViewState
There are several options to cut down on the bloat (and yes, there's a lot of it when dealing with lots of controls):
Use AJAX to post only the items required - although be careful to allow clients that don't have JavaScript enabled to still use the page/ site.
The MVC framework allows multiple form tags to be used so you can group sections if needs be.
Set the EnableViewState to false on pages/ controls.
Break up your pages into smaller ones.
Additionally, check out this brilliant graphical representation of the Page Life Cycle in ASP.NET.
Every input on the page is posted back fully unless you use ajax, because of the single form tag. Welcome to asp.net...
As long as the method that you're hitting on the server-side is a non-static member of the page's class, it'll have access to the textbox and all other controls on the page.
And yes, all controls rendered to the browser (whether in the MasterPage, user control, etc.) will be available on post-back.
You may want to look into Understanding ASP.NET View State.
There surely are performance hits with this architecture, but (depending on complexity of the page) it's usually not an issue from the server load perspective, because hardware upgrades are typically cheaper than additional programming hours spend on optimizing application performance.
With that said, (and as others have pointed out) look into using AJAX if you want to avoid whole page-level postbacks to the server.
Yes, it's all posted back, and yes it can cause bloat. I'm sure if you search for ViewState you will find plenty of people ranting about it and how to minimise it :)
Yes your text box will be available in both cases, yes it is bloated. This is where AJAX comes into play. Using AJAX you can send just the data you need.
If you want to send a minimal ammount of data, you could use a Page Method (static method on page decorated so the script manager builds javascript to call it or you could call it using jquery or other methods), or a script enabled web service works nice as well.
You also have viewstate which can get very large. ASP.Net MVC is a new paradigm instead of using WebForms which doesn't have view state, or post backs. It embraces HTTP instead of hidding it giving developers more control.
The textbox data would be posted back as noted. In addition to using Ajax, disabling view state greatly imporoves your page's performance though even then data in properties critical to the functioning of controls (Control state) would still be posted back.
If you didn't have postback for every control on the form, you wouldn't be able to access it in code-behind. I.e. if in your button press you wanted to modify the property of the text control you couldn't do that because ASP.Net would know nothing about the text control.
Since the communication between the server and the client is stateless and every time a page is server the server forgets all about it Postbacks are important if you want to work with the same page again. No matter what programming language you use, this or similar mechanism exists for processing server side code.
If you wish to minimize postback (viewstate size), do this.
Set enableviewstate=false on all controls that you don't want posted back.
Use AJAX and web services wherever possible (and don't use UpdatePanel).
Use HTML control as much as possible instead of ASP.Net controls.
Hmm.. There are some excellent suggestion in other answers and good links too.
You've pretty much hit the nail on the head with vanilla ASP.NET - it's not very good! In both the instances you describe the answer is yes - the textbox will be sent with the form.
The whole postback/ViewState problem is a bit of a pain, one of the first things any competent ASP.NET developer learns to do is avoid them!
I am moving from classic ASP to ASP.NET and have encountered what many of you already know as "viewstate". I might be jumping the gun with my assumption, but it looks highly cumbersome. I have developed many ASP forms in the past and never had issues with keeping state. Is there another way OR am I going to have to learn this Viewstate thing in ASP.NET? I am using Visual Studio 2008, VB.NET as the code behind language and Framework v3.5 with SQL Server 2005.
You don't have to. Check out MVC framework. It eliminates ViewState and works as old ASP (at least from this point of view).
This series of posts is must reading for understanding ViewState
I disable it and do most of my work in Page_Init instead of Load (values are still maintained because of ControlState). This setup has worked out well for me.
ViewState is optional, but helpful. What ViewState is, is all the changes which occur on a control on the SERVER SIDE. So, if you're assigning text to a label, and you want that text to persist without the need to reassign it on every postback, then you'll want to maintain that. Another example where I always leave ViewState on is anything databound.
That said, there are times when it's helpful to turn ViewState off for that same reason. For example, the one place where I always turn ViewState off is a MESSAGE label. That way, when I have to print out a message to the user (one which should only appear once and then go away) I just add the text to the label and then forget about it. During the next PostBack, the label will automatically revert to the text which is found in the ASPX declaration for that control (in this case an empty string).
Now, note that this has nothing to do with the form collection, which are the values posted to IIS during the PostBack. The form collection sends the values that the user enters into form elements (textboxes, checkboxes, droplists,etc). These .NET will populate into the appropriate place--and this occurs AFTER ViewState has been processed.
This way, if you send a textbox with the phrase "hi there" to the client, the user changes it to "See ya" and then submits the form, what the textbox will have by the time the Page_Load event fires is a textbox with "See ya" in the TEXT attribute.
In classic ASP we always just used a HIDDEN field to do the job. Viewstate is just a way of doing that for you automatically. Trust me the learning curve is not as high as you might think.
Some controls are deeply crippled when you turn ViewState off, so be prepared to address these concerns. It's easiest to just be lazy and leave it on, but left unchecked, ViewState can easily account for 30% of the size of your HTML.
For example, say you have a DropDown, and you bind it to a list of Fruits. You bind it in the if(! IsPostBack) { } block in the page load. If you turn off ViewState, you'll lose the items when you click a button. They need to be bound every page load. You'll also lose your selected index, so you'd need to pull that off of the Request.Form[] variables.
Viewstate is part of the package when you are working with ASP.NET. For a basic page/website you shouldn't have to 'know' how to use Viewstate. It just gets used as you put controls on pages.
It's pretty hard to avoid Viewstate with ASP.NET because even if you turn it off at the project level, some individual controls still use Viewstate to persist their information.
If you don't want to deal with Viewstate, consider using the ASP.NET MVC framework. You will likely be more comfortable with the MVC framework coming from Classic ASP.
ViewState is completely optional in almost all if not all cases. ASP.NET re-populates fields automatically even if ViewStateEnabled=false. I've been using ASP.NET for 5 or 6 years and have never had to depend on ViewState. I even disable it when I can.
ViewState works automatically for the most part. It's just how ASP.NET keeps track of the current state of all it's controls.
You can manually use viewstate too, if you want to store some extra data. That is as simple as:
Viewstate["Key"] = value;
The only caveat with that is that any object you store in viewstate must be serializable.
I can definitely recommend avoiding ViewState in DataGrids and DropDownLists because I just recently started doing it myself. I didn't do this for fun, I had to fix a page that had grown so large that it was causing other problems. But this turned out to be easy, and the results were so dramatic that I am very pleased. Of course for a small simple app or for small amounts of data this will not be necessary, but on the other hand it's good to be consistent (always go from known to known so you can continually improve your process...), and why carry around extra baggage, ever?
This will require a little manual intervention on your part. For example, if you turn off viewstate for drop down lists, you'll need to rebind them on each postback, and then restore the SelectedValue from the Request object. You'll need to read up on this, but google has lots of readily available information.
Viewstate is kept automatically for asp.net controls "rooted" to the page. There is little you have to do, the values and some other information is passed in a hidden input B64 encoded. You can look at it if you want, but it doesn't matter, it's all handled automagically for you.
If you're writing code for your own consumption, you can just turn it off and not worry.
Presumably you're going to maintain Web Forms code written by other people, so you should know what the config options and pain points are. Top few I can think of
how to disable it at site, page and control level
why MachineKey is relevant in web farms
why your event log is full of ViewStateAuthentication errors
what ViewStateUserKey is
In terms of actual learning curve this is probably a thorough read of a couple of MSDN articles.
ViewState is a necessary evil inherent to the web forms metaphor. I personally find this methodology obsolete, bloated and generally not web-friendly. Better check out MVC framework as suggested above.
I suggest you avoid the temptation to use ViewState as a "cache" to pass data back and forth (I've seen websites doing this because of clustered setup and no SQL-backed session state). The data is serialized and added to the page and must do roundtrips every request, adding to the total size of the page and making your site slower to load.
'<%# Control Language="C#" AutoEventWireup="true" CodeFile="HomePage.ascx.cs" Inherits="HomePage" %>
<script runat="server">
void testHF_ValueChanged(object sender, EventArgs e)
{
this.HFvalue.Text = this.testHF.Value ;
}
</script>
<asp:Label ID="UserNamelbl" runat="server" Text="User Name : " Visible="false"></asp:Label>
<asp:TextBox ID="UserNametxt" runat="server" Visible="false" ></asp:TextBox>
<asp:Label ID="HFvalue" Text="......" runat="server"></asp:Label>
<asp:HiddenField ID="testHF"
OnValueChanged="testHF_ValueChanged"
value=""
runat="server" ></asp:HiddenField>
<input type="submit" name="SubmitButton" value="Submit" onclick="CL()" />
<script type="text/javascript">
function CL()
{
this.testHF.Value = this.UserNametxt.Text;
}
</script>
'