JQuery output a dynamic control in a div - asp.net

How do I handle the click of a checkbox to show another control preferrably a user conrtrol (ASP.NET ) dynamically.

I don't know anything about the system you're using but the low down dirty way I'd do this is...
Stick the user control on a blank page of it's own.
When the checkbox is clicked, have JQuery go get the HTML content of the page the user control is on and stick it in the div.
This will result in not-so-neat html in the calling page though.
And is this an asp:CheckBox or an html input?

If you want to create a new object, you can do this:
var checkbox = $("<input type='checkbox' ... />");
$('div#someID').append(checkbox);
Though it sounds like you perhaps want to get the data to append from an AJAX call. I can't quite tell from the question.

Assuming you hide the control with CSS by default you could shorten TStamper's code to something like:
$(function() {
$('#checkbox').click(function() {
$('#control').toggle();
});
});
<mycontrol:UC id="control" runat="server" />

I'm partial to using jquery's taconite plugin. It enables you to return multiple controls from a single ajax call.
For a simple show/hide control scenario rendering a hidden control on a page is good enough. If your control is big or changes due to user actions then your best bet is rendering control on the server and using js to update DOM.
If you're using jquery for your DOM updates and wish to find control by id use:
$("[id$=controlId]")
This will locate your control even with asp.net prefixes to the id.
I'm working on a simple c# wrapper for the taconite plugin which should enable you to use the plugin more easily (sample web site coming soon).

Are you looking for something like this:
$(function(){
$('#Control').hide(); //initially hide the control
$('#checkbox').click(function(){ // bind the checkbox click event
if ($('#checkbox').attr('checked')) {
$('#Control').show();
}
});
});
<mycontrol:UC id="Control" runat="server" />

Related

How to run a javascript function before postback of asp.net button?

I'm using Javascript to create a DIV element and open up a new page by using onclientclick. This works great. Now, I need to write to it from the server side and this element must be created before it is posted back.
How do I get the javascript to execute before the postback?
Currently, I have to press the button twice because the element doesn't exist to write too on the first click.
To be clear, I need this to execute before the "OnClick" of the button.
Update: It looks like the Javascript function is called before the postback but the element is not updated until I run the second postback. Hmm
Update: Unfortunately it is a bit more complicated then this.
I'm creating a div tag in javascript to open a new window. Inside the div tag, I'm using a databinding syntax <%=Preview%> so that I can get access to this element on the server side. From the server side, I'm injecting the code.
I'm thinking this may be a chicken-egg problem but not sure.
UPDATE!
It is not the Javascript not running first. It is the databinding mechanism which is reading the blank variable before I'm able to set it.
Hmm
you don't have to rely on server controls to perform postbacks in asp.net. you can gain finer control of your app by posting from javascript whenever you are ready..
the framework auto generates a function called __doPostback(.....) and eventually calls it every time it needs to do a postback.
so. instead of using server control button, you can have a regular <button onclick="foo()" />
than once you're done performing all that you need, just call the __doPostback function.
asp.net gives you a nifty way to access that function with
Page.GetPostbackClientEvent (i believe, but there are couple methods that support this methodology)
http://msdn.microsoft.com/en-us/library/system.web.ui.page.getpostbackclientevent.aspx
enter code hereWould this work for you?
Javascript
function stuffYouWantToDo(){
//do your stuff
//then submit the .NET form
document.forms[0].submit();
}
.NET code
<asp:button ID="Button1" onClientClick="return false;stuffYouWantToDo();"/>
This should ensure that the stuff you want to do is done, then the form will be submitted. The return false prevents the form from being submitted when you first click the button and relies on the call in the stuffYouWantToDo function to submit the form.
If you want to use jquery you could do the following:
$(document).ready(function() {
var execScript = $(".myButton").attr("href").replace("javascript:", "");
$(".myButton").attr("href", "#").click(function() {
// Add before click logic here
eval(execScript);
});
});
Couldn't you simply add a custom validator somewhere in your form?

Can I assume asp.net form's ID always being the same?

I want to submit a simple asp.net form in jQuery
can I assume
$("form[0]").submit()
always works, cross browser?
You mean something like this
$("#aspnetForm").submit()
Something like above would work cross browser as you said
The code you pasted is cross browser too. It won't work on ANY browser so maybe that counts as cross browser :-) just a joke
No, you can't assume this. $("form[0]").submit() will submit the first form on the page. However, you can have more than one form on an ASP.NET page, though only one of these forms can be a server-side form (with runat="server" attribute).
If what you want is to submit the server-side form on an ASP.NET page then I think the best way would be to do it in code-behind by registering a script. It's a bit more hassle, but should always work (and when there is no server-side form it will detect it). Something like this:
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (this.Form != null)
{
string js = String.Format("$('#{0}').submit()", this.Form.ClientID);
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Submit", js, true);
}
}
These will:
$("#aspnetForm").submit()
or
var theForm = document.forms['aspnetForm'];
theForm.submit()
If you know that this code will be triggered by an input or button element within the ASP.NET form, or if you can select a known input or button element within the ASP.NET form, you can use input.form.submit();.
Usage examples
this.form.submit();
or
$("#some_input_or_button").get(0).form.submit();
Although reading the input.form/button.form property does not use jQuery, it is at least as cross-browser since jQuery itself does this.
Benefit: This method allows you to avoid dependence on the form ID generated by ASP.NET's internals without having to add any extra wiring server-side.

Add an Editor control dynamically inside of a repeater using AJAX

I'm looking for a way to add an Editor control (from the ASP.NET AJAX Control Toolkit) to each element of a repeater. It's working fine if I just include it in the ItemTemplate of the repeater, but my problem is that the markup it produces is massive, which slows down the page considerably (even with compression on).
I haven't had any luck adding the control inside the repeater item using an Update Panel - I think this is probably the preferred method, but dynamically adding a control inside an Update Panel inside of a Repeater Item isn't something I've had any success doing, and there don't seem to be any good examples of this that I can find.
The other alternative I considered was using PageMethods to render the control and send the HTML back to the page to let the javascript put it in the appropriate place, then deal with it, but it won't let me render the control - I get an InvalidOperationException of "Page cannot be null. Please ensure that this operation is being performed in the context of an ASP.NET request.". My guess is that all the javascript that's generated makes it so that I can't just render an Editor control on the fly.
Can you point me in the right direction for accomplishing this?
Thanks
EDIT: Another alternative, if it is possible, would be to put a normal Editor control in the markup of the page, then move it around inside of the repeater as needed, using javascript. I can do this with normal controls, but when I do it with an editor, it is not behaving nicely - the textbox appears, but won't let me click inside it. If you have any ideas on this one, I'd appreciate that as well. Here's the code for this:
<span id="spanHiddenEditor" style="display: block;">
<cc1:Editor ID="ed1" runat="server" Height="200" Width="400" />
</span>
<script type="text/javascript">
function createTextBox(idx) {
var span = $get("span1_" + idx); // this gets me the target location
var hiddenEditorSpan = $get("spanHiddenEditor")
var editorHtml = hiddenEditorSpan.innerHTML;
hiddenEditorSpan.innerHTML = "";
span.innerHTML = editorHtml;
}
</script>
identify the location within the repeater with a class then use jquery to inser the html on page ready
$(function() {
$(".myclass").Append("<htmlz>");
});
Then if you need to identify each text box you can do it using the parent container ID eg.
$("#myID div.class input").value
I'm a total jquery newb so none its likely none of it will work, but i believe the idea is a good one!

jQuery and ASP.NET Control issue

If I have a custom ASP.NET control that renders as an html control with an ID, I'm trying to add an attribute to the input control with jQuery.
However, I'm running into some issues:
First, my jQuery is not able to select it.
I have so far:
$(document).ready(function() {
$(client id of the input control).attr('onclick', function () { alert('hey!'); });
});
It seems as if the jQuery is trying to find the input control but cannot.
Any ideas?
UPDATE:
Normally, the solutions presented would work but since this is a SharePoint Publishing .aspx page, Code blocks are not allowed... Trying other work arounds.
Just wire up the click event in jQuery.
$(document).ready(function() {
$(id of the input control)click(function() {
alert('hey!');
});
});
Also, make sure you aren't just putting the ID you typed in to the control in the jQuery. ASP.Net renders the control with a much different ID than you had given the control. On one of the sites I run, I have the following button:
<asp:Button ID="btnSignup" runat="server" Text="Sign Up" />
The ID in the rendered HTML is not btnSignup, it actually renders as ctl00_cpLeft_btnSignup. To select that control with jQuery, you can do this:
$("input[id$='btnSignup'").click(function() { ... });
Edit:
$("input[id$='btnSignup'}").click(function() { ... });
You can also select using:
$("#<%= btnSignup.ClientID %>").click(function() { ... });
Edit:
I looked into using the <%= ... %> method and you would have to have your javascript IN the ASPX/ASCX file itself for it to work. Because of this, I'd stick with the regex method.
What do you use as the ID of the input control?
You have to use the ClientID of the control, not it's ID.
You need to use its ClientID. If your ASP.NET markup looks like this:
<uc:MyControl runat="server" ID="myControl1" />
Your jQuery selector should look like this:
$(document).ready(function() {
$("<%=myControl1.ClientID%>").attr('onclick', function () { alert('hey!'); });
});
Selecting a ASP.NET generated ID with jQuery
Is your ASP.NET control in a master page or a user control? ASP.NET will prepend a bunch of identifiers to your ID to make sure it is unique.
What is the ID of the control coming out as in HTML?
If you're setting the ID of the rendered HTML control to the ID given to the ASP.NET control, you need to be aware of how ASP.NET handles control ID namespaces. Essentially, each control nested within a control needs to always guarantee a unique identifier. ASP.NET maintains this by taking the ID assigned to a control and prepending it with the ID of every control that contains the control. Thus, a control on a page will contain a string of ids going up to the form on the page itself.
You do not want to have to re-construct this client-side. Instead, Control defines ClientID, which will return the ID of the control as rendered on the client. Embed this into your jQuery, or into a javascript variable that your jQuery can see if you are putting the jQuery in a separate script file) and you should be fine.
just to inform you, the document.ready part is not needed, using asp.net control the id is changed to something different then what is expect, a ct100.... is thrown on the beginning of it, so this way will look for the actual id name even though asp.net throws the mangled code on the beginning,because it looks for all elements (*) that have an ID that ends with the specified text.
$(function() {
$("*[id$='idofcontrol']".click(function() { alert('hey!'); });
});
or go to the view source and copy the id name and paste it in your code or just use the css class selector as so:
$(function() {
$('.myclassname').click(function() { alert('hey!'); });
});
Since you mentioned Sharepoint you might be interested in this series on EndUserSharepoint that focuses on integrating jQuery with Sharepoint. The author discusses getting jQuery to manipulate the webparts.

Easiest/Best Hide/Show Client Side Hide/Show for ASP.NET

I have a DropDownList and a TextBox on a Page. When the user chooses the "other" option in the DropDownList I want to display a TextBox just to the right of it. I do not want to use the traditional PostBack technique. I want this interaction to be client side.
I am aware that I can get a get a reference to the DOM element and set its style to "display:none" or "display:". What I am looking for is something that is built into the ASP.NET framework for handling something like this. I mean, in jQuery this is as simple as $('controlID').hide. Is there a Control Extender that can do this? Is jQuery part of the ASP.NET framework yet?
jQuery will be/is distributed with VisualStudio/ASP.NET MVC, though I wouldn't call it part of the framework. I think that you can feel free to use it and trust that it will be supported.
Note that Microsoft has said that they will be using the main line of development for jQuery so the code itself won't be any different than you can download from jQuery.com, except perhaps for built-in Intellisense.
EDIT: To set up your functionality download the code from jquery.com. Put it in your scripts folder, or wherever you store javascript stuff. Add a script reference for it to your page. Use jquery to add an onchange handler to your dropdown list and when the value of the dropdown list is other show the textbox, otherwise hide it. The example below assumes that other isn't the default selection. If you are using runat="server" controls with MasterPages or inside UserControls, you'll need to adjust the names in the javascript functions to account for the name mangling that ASP.NET does. Probably simpler to give them unique CSS classes and reference them using the ".class" notation rather than "#id" notation.
<script type="text/javascript" src="...pathtoscript../jquery.1.2.6.js"></script>
<script type="text/javascript">
$(document).ready( function() {
$("#DropDownListID").bind('change', function() {
if (this.options[this.selectedIndex].value == 'other')
{
$("#TextBoxID").show();
}
else
{
$("#TextBoxID").hide();
}
});
});
</script>
...
<select id="DropDownList">
<option value='first'>First</option>
...
<option value='other'>Other</option>
</select>
<input type='text' id='TextBox' style='display: none;' />
You could also use the asp.net client side framework(via the scriptmanager) to get a reference to the element. But then you still have to use the normal DOM manipulation.
$get('<%= myDropDown.ClientID %>').style.display = 'none';
Just make sure you have the script manager referenced.
For something so simple, I wouldn't think it is worth referencing jquery, but maybe you've got bigger plans ;-)

Resources