Server Controls via Response.Write - asp.net

I am trying to write chunks of html to a .aspx page from a .ashx handler file. In the handler file, I am trying to write a server tag
<asp:updatepanel id="UpdatePanel6" childrenastriggers="True" updatemode="Always" runat="server">
<contenttemplate>
<ajaxtoolkit:rating id="Rating6" autopostback="True" emptystarcssclass="Empty" filledstarcssclass="Filled" waitingstarcssclass="Saved" starcssclass="ratingItem" cssclass="ratingStar" currentrating="2" maxrating="5" runat="server"> </ajaxtoolkit:rating>
</contenttemplate>
</asp:updatepanel>
But this is not displayed on the corresponding .aspx page. When I inspect it in firebug, I see the code chunk there rather than the executed piece which should be something like
<div id="UpdatePanel11">
<div id="Rating11" class="ratingStar">
<input id="Rating11_RatingExtender_ClientState" type="hidden" value="2" name="Rating11_RatingExtender_ClientState">
<a id="Rating11_A" style="text-decoration:none" title="2" href="javascript:void(0)">
<span id="Rating11_Star_1" class="ratingItem Filled" style="float:left;"> </span>
<span id="Rating11_Star_2" class="ratingItem Filled" style="float:left;"> </span>
<span id="Rating11_Star_3" class="ratingItem Empty" style="float:left;"> </span>
<span id="Rating11_Star_4" class="ratingItem Empty" style="float:left;"> </span>
<span id="Rating11_Star_5" class="ratingItem Empty" style="float:left;"> </span>
</a>
</div>
Could someone help me with pointers on what I am missing here ? Thanks !

You can't do this. Response.Write injects directly into the output stream, without any processing. An .aspx page generates its output by building a control tree (consisting of the literal markup and the control tags in the .aspx file), and possibly adding more controls dynamically in code. Then the nodes of the tree are evaluated in top-down order to generate the HTML, which they send back to the browser through Response.Write calls.
Unlike an .aspx page, an .ashx handler does not deal with controls -- there is no control tree. You are responsible for reading the request and producing the raw response text yourself.
It sounds like you're trying to dynamically create controls; in that case, use an .aspx file and add controls to the tree in the codebehind file.

as Carl mentioned this is going to be a little hard to accomplish. If what you need to do is just to create a dynamic Rating thing, I would suggest to use page.Controls.Add and add handlers to them so that they can handle when an user clicks on them. If you need help please let us know.

Related

how to trigger asp.net multiview?

I'm still getting my head around asp.net.
I followed some online examples of using multiviews and got them working just fine when I use something like a Menu class as the trigger to select the active view. Having the onClick event makes it pretty easy.
But I can't figure out how to change the emmited code from the Menu control.
I have the following multiview control...
<asp:View ID="0" runat="server">
<p>view page 1</p>
</asp:View>
<asp:View ID="1" runat="server">
<p>view page 2</p>
</asp:View>
And I need to have the following structure used to trigger the views.
(Note: this needs to be what gets emitted to the browser. Not necessarily the literal code in the aspx page)
<a class="button large-plain" href="" >
<span>
See page 1
</span>
</a>
<a class="button large-plain" href="" >
<span>
See page 2
</span>
</a>
For clarification: we have a style sheet provided by an exteranl designer that works with the above markup. If I could just make the triggers asp button controls, or a menu control, it would be easy. But the style sheet doesn't work then, and I'm told the world will end if the style sheet doesn't work.
Can I customise a Menu control so that it outputs this kind of structure? (And if so, how?)
I could just hard code the links that trigger the views (the structure is not going to change). But if I hardcode it, how do I call the onClick event what the links are clicked?
I think you might be able to try the following to change the tags into server-side controls and then use that as the trigger. Adding ID and runat="server" to any html element means that you can then access them programmatically as you would any other .NET style control. Additionally if you're using .NET 4.0 you can also add the ClientIdMode="Static" attribute so that the ID's are as you typed and not modified by ASP.NET.
To solve the Click problem you can add the OnServerClick="" attribute to specify which method to call on the server when the link is clicked.
<a class="button large-plain" href="" ID="ViewPage1" runat="server" OnServerClick="ViewPage1_Click">
<span>
See page 1
</span>
</a>
<a class="button large-plain" href="" ID="ViewPage2" runat="server" OnServerClick="ViewPage2_Click">
<span>
See page 2
</span>
</a>

Javascript won't work on Html server control?

I am writing a website with ASP.Net.
I will have lots of html generic controls like <div> <span> and so on..
I have some onclick javascript functions, onmouseover javascript functions..
They are working fine..
Then I need to control them on the server side.
So, I add runat="server"..
After that, all the javascripts aren't working anymore..
I understand they aren't working coz all the events are now going back to server side.
So, is there anyway to make them work??
For eg,
<div id="myDiv1" onclick="myfunction(para1)"><img src="..." /></div>
the above code is working..
<div id="myDiv1" runat="server" onclick="myfunction(para1)"><img src="..." /></div>
the above code is not working...
I can make it work, probably by
<div id="externalDiv1" onclick="myfunction(para1)"><div id="myDiv1" runat="server" ><img src="..." /></div></div>
Is there any other way?
I assume that you used document.getElementById() to get an element by its id. If you are using master pages, the IDs of server controls will be changed after rendering to the page, in that case, you have to use its ClientID
for e.g.
var myDiv1 = document.getElementById("<%= myDiv1.ClientID %>");
Server-side or client-side controls makes no difference as far as javascript is concerned. ALL server-side controls end up being rendered as normal HTML controls. If your javascript functions are not working might be because you are accessing them by the wrong id since by making them server-side controls they can now have ids that follow a pattern like <parent_id>_<control_id>.
For example, a span element declared like this:
<span id="mylabel" runat="server"> testing</span>
may end up being rendered as:
<span id="MainContent_mylabel"> testing</span>
ASP.NET 4.0 has a feature called CliendIDMode which can be set to static, meaning, that your ids on the markup will stay unchanged after the page is rendered.

Including Javascript with a custom control in an ASP.Net website

I have a custom date control which is essentially a text box and the ajaxToolKit calendarExtender. I want to include Javascript in the control and have it work properly no matter what page the control is on. The control is called DateControl.ascx
So I have two Javascript functions, dateEditor_OnShown and dateEditor_OnHiding. They get tied up in the page load of DateControl.ascx via...
CalendarExtender.OnClientShown = "dateEditor_OnShown";
CalendarExtender.OnClientHiding = "dateEditor_OnHiding";
The DateControl tool is used on two separate pages. If I put the straight Javascript directly into the DateControl's HTML it will work only on the default page but crashes when I load up the next page with the control. The error is a js runtime error 'dateEditor_OnHiding' is undefined.
If I try to link to the Javascript file from my DateControl's html via...
<script type="text/javascript" src="../JavaScript/IE6CalendarExtenderFix.js"></script>
... instead of having the Javascript directly in the page, it crashes immediately with the same error. I should note that the path to the js is correct.
The only way I can really get it to work is if I link to the javascript on every page that the control is used.
UPDATE: I feel the need to clarify a little bit. The solutions suggested are much appreciated, but either I am not understanding or they just will not work in my case for whatever reason (quite possibly the former).
So, this is basically what my control looks like...
<div id="CustomDateControl" style="<%# ControlStyle %>">
<div id="TextBox" style="display:inline; white-space:nowrap;">
<asp:TextBox runat="server" ID="txtCalender" Style="<%# TextBoxStyle %>" />
</div>
<div id="Calendar" runat="server">
<ajaxToolkit:CalendarExtender
runat="server"
ID="CalendarExtender"
Format="MM/dd/yyyy"
TargetControlID="txtCalender"
PopupButtonID="CalenderImage" />
</div>
</div>
In the aspx page, with that exact code, if I put the exact javascript in script tags so the page looks about like so...
<script type="text/javascript">
function dateEditor_OnShown(dateControl, emptyEventArgs) {
...
}
function dateEditor_OnHiding(dateControl, emptyEventArgs) {
...
}
</script>
<div id="CustomDateControl" style="<%# ControlStyle %>">
<div id="TextBox" style="display:inline; white-space:nowrap;">
<asp:TextBox runat="server" ID="txtCalender" Style="<%# TextBoxStyle %>" />
</div>
<div id="Calendar" runat="server">
<ajaxToolkit:CalendarExtender
runat="server"
ID="CalendarExtender"
Format="MM/dd/yyyy"
TargetControlID="txtCalender"
PopupButtonID="CalenderImage" />
</div>
</div>
This still crashes when accessing the control in the second page (not the first which is the default page) saying 'dateEditor_OnHiding' is undefined. Now, if I link to a js file with the same code using a relative path as suggested below I still get the same results.
Also, if as suggested below, I override OnPreRender and run RegisterClientScriptInclude, I once again get the same results. The control always works on the default page but never on the second page even though as far as I can tell the script is included in the control.
Any ideas?
append following code in your User Control.
protected override void OnPreRender(EventArgs e)
{
Page.ClientScript.RegisterClientScriptInclude("DateControl", this.ResolveClientUrl("~/JavaScript/IE6CalendarExtenderFix.js"));
base.OnPreRender(e);
}
Problem with control-relative file paths
You are probably having problems with relative paths to your JS file. You are specifying relative path to your custom control. You should probably write user control. Anyway. Your JS file is relative path to your custom control, but not relative to the containing page, so your JS file actually never loads. That's why your event handlers are undefined.
The easiest way would be to use absolute paths. Since you're working with user controls you can easily prepend application root folder.

Expanding ClientID in an event string

I'm having a problem with <%= obj.ClientID %> expansion, in a .ascx user control.
I have a .js file, containing a javascript function:
function doSomething(objectId)
{
...
}
I have a .ascx file, with some html elements, and in one element's onclick= I want to call doSomething(), passing the ID of an element in that .ascx file, where the passed ID is of an element other than the one being clicked on, so I can't use "this.".
Maybe it'd be clearer with an example.
This works:
<script type="text/javascript">
function redirect()
{
doSomething('<%= top.ClientID %>');
}
</script>
<div id="top" runat="server">
<img src="..." alt="..." onclick="redirect();"/>
</div>
But this does not:
<div id="top" runat="server">
<img src="..." alt="..." onclick="doSomething('<%= top.ClientID %>');"/>
</div>
When I look at the source, I see that the <%= %> substitution has not happened, instead of "doSomething('ctl00_myControl_top');" I get "doSomething('<%= top.ClientID %>');"
For some reason, the script expansion happens in the former case, but not in the latter. The work-around, of course, is not acceptable because it will break if I include multiple copies of the control on a page - only one instance's "redirect()" function will be accessible.
Any ideas on how to make this substitution work?
Works on my machine?
<div id="top" runat="server">
rarrarara
</div>
Becomes
<div id="ctl00_ContentPlaceHolder1_top">
rarrarara
</div>
Consider an alternate route:
Ensure that the control you are referencing in JavaScript using the inline expression <%= (controlName).ClientID %> has its 'ClientIDMode' specifier set to a static value and then simply use the text in the ID field of that control to refer to it. I ended up using this in a recent project it works great. Please see the link below for a more detailed explanation:
Code Project - ASP.NET v4.0 Client ID Feature
Along with setting the 'ClientIDMode' specifier to "Static", I found a useful idea regarding placing text from a global resource file (in the case of language switching) into a field of a standard HTML control that does not have to run at the server level. I used this on a standard HTML button that was supposed to call a JavaScript function that would show/hide a specific div or ASP Panel. Use the GlobalResource function in the inline expression tags like so:
<input id="btnToggleFilterOptions" type="button" value="<%=GetGlobalResourceObject("SiteResource", "btnToggleFilterOption")%>" onclick="javascript:ToggleCssClass('divFilterOption','visible'); return false;" class="button submit" />
<asp:Panel ID="divFilterOption" ClientIDMode="Static" runat="server">
<asp:TextBox ID="txtFilterOption1" runat="server" />
</asp:Panel>
I know this is an old post, but it is a popular hit when searching on Google for Asp .NET and ClientID. I hope this helps somebody else out!

What is the minimum amount of HTML an UpdatePanel requires before it falls over?

If for instance, I was to give a response back to an ASP.Net Update Panel page, but use Response.Write and then end it before anything was rendered, what is the minimum I would need to write in the Response.Write?
If you take the following UpdatePanel ...
<asp:UpdatePanel runat="server" id="updatePanel" ChildrenAsTriggers="True">
<ContentTemplate>
<asp:TextBox runat="server" ID ="textbox1"/>
<asp:Button runat="server" ID="go" OnClick="OnGo" text="Go"/>
</ContentTemplate>
</asp:UpdatePanel>
... then click the button and view the response in Firebug, you'll get something like this (I've truncated the viewstate and event validation to make it a bit more readable):
265|updatePanel|updatePanel|
<input type="text" name="textbox1" value="content" id="input1" />
<input type="submit" name="go" value="Go" id="go" />|
52|hiddenField|__VIEWSTATE|/wXPZwUK...|
64|hiddenField|__EVENTVALIDATION|/wEWB...|
0|asyncPostBackControlIDs|||0|postBackControlIDs|||
12|updatePanelIDs||tupdatePanel|0|childUpdatePanelIDs|||
11|panelsToRefreshIDs||updatePanel|2|asyncPostBackTimeout||90|20|
formAction||Upagename.aspx|13|pageTitle||Untitled Page|
All that extra data is stuff that the ScriptManager needs to rebuild the contents of the UpdatePanel: control ids, the page name, viewstate, etc.. This is what you'd have to Response.Write manually for the ScriptManager to be able to do its job.
For details, see "ScriptManager Enables AJAX In Your Web Apps". At the end of the section titled "Putting the AJAX in ASP.NET AJAX", the author explains what's going on:
Finally, the client framework gets the
asynchronous response from the server
and parses out data. The ScriptManager
control has packed into the response
all the control IDs and new markup so
the client framework can simply
perform scripting operations on the
browser's document object model to
update the page content.

Resources