To get value from user control using ajax - c#

I have datalist in field.ascx and i have a label and textbox in fields.ascx and i am binding textbox and label dynamically in datalist and display in webform.aspx.Now i want to get label text and textbox value in webform.aspx when clicking a button in webform.aspx using ajax.
field.ascx:
<asp:DataList ID="dtlist" runat="server" RepeatColumns="4" CellPadding="5" EnableViewState="True">
<ItemTemplate>
<data:Value ID="test" runat="server" />
<ItemTemplate>
</asp:DataList>
Fields.ascx:
<asp:Label ID="lbl" runat="server" />
<asp:TextBox id="tb4" runat="server" />
Webform.aspx
<button onclick="myFunction()">Click me</button>
[WebMethod]
public static string LoadUserControl()
{
using (Page page = new Page())
{
HtmlForm form = new HtmlForm();
UserControl userControl = (UserControl)page.LoadControl("UserControls/field.ascx");
form.Controls.Add(userControl);
using (StringWriter writer = new StringWriter())
{
page.Controls.Add(form);
HttpContext.Current.Server.Execute(page, writer, false);
return writer.ToString();
}
}
}

You are destroying the values in the user control within the following line of your ASP.NET AJAX page method:
using (Page page = new Page())
In reality, you don't have access to the Page object at all within an ASP.NET AJAX page method, because it is static and does not at all interact with the ASP.NET Page Lifecycle.
If you are only going to have one instance of your user control, then you could use jQuery selectors in your myFunction JavaScript function to pull out the values for the Label and TextBox controls (be aware of the container naming that ASP.NET uses for master pages, and the control hierarchy). You can then build up an object literal to pass to the ASP.NET AJAX Page Method via the jQuery .ajax() function.
If you are going to have multiple instances of the user control on your page, then you will be better off using a server-side solution, coupled with the ASP.NET UpdatePanel control to give the illusion of asynchronous calls to the server (read: less screen flickering, because of only a partial postback). In this case, you can have public properties of the values you want to pull out of the user control and your server-side code will have references to each of the user control instances by ID.
So bottom line is that if you do not need to actually use a client-side JavaScript function to make a call to the server, then just use the server-side button click handler to do the logic of getting values from the server-side controls. The water quickly gets muddied when trying to get values out of server-side controls that could have multiple instances.

Related

Search ImageButton in Repeater

I have a TextBox:
<asp:TextBox ID="textSearch" runat="server" Width="80" ForeColor="Black" />
and a Repeater with ImageButtons:
<asp:Panel ID="panRepeater" runat="server" ScrollBars="Vertical">
<asp:Repeater ID="Repeater" runat="server">
<ItemTemplate>
<asp:ImageButton ID="imgSearchResult" runat="server" ImageUrl='<%# Eval("ImageUrl") %>'/>
</ItemTemplate>
</asp:Repeater>
</asp:Panel>
In code behind, I add the Images to the ImageButtons with this function:
private void LoadImages()
{
string[] filesindirectory = Directory.GetFiles(Server.MapPath("~/Images/ORAS"));
List<System.Web.UI.WebControls.Image> images = new List<System.Web.UI.WebControls.Image>(filesindirectory.Count());
foreach (string item in filesindirectory)
{
System.Web.UI.WebControls.Image image = new System.Web.UI.WebControls.Image();
image.ImageUrl = (String.Format("~/Images/ORAS/{0}", System.IO.Path.GetFileName(item)));
images.Add(image);
}
Repeater.DataSource = images;
Repeater.DataBind();
}
I want to be able to search and only display the wanted ImageButtons similar to this example:
I would type in 00 into the Search-TextBox and all ImageButtons, which contain 00 will be shown. The thing is that I'd have to do this after every KeyDown.
This is a complex scenario and can be implemented in two different ways.
Using ajax postback by hooking up a server-side text changed event of search textbox. In this server-side event, you would get records from database using the search text box text value. An example of a similar scenario using gridview can be found at this URL: Server-side Search
The second approach, which is more prefered is calling the server-side method to get records directly from JavaScript or jquery. This can be very quick and fast. An example of such a scenario using gridview can be found at this URL: Search using client-side code.
For the second option, you have to hookup client-side keyup event to get search text before making an ajax call to a web service method from jquery, and also only do a search if user has input a minimum number of characters like 2 or 3 or 4 or whatever you think is a good number. The web service method on server-side will return a JSON collection of the searched items for your repeater control. Finally, in the success event of jquery ajax call you would need to populate the repeater items with the search items.
A Suggestion
Also, as another suggestion to make it easier to implement the client-side solution you could create an html string in the web service method and then in success event of jquery ajax call just set the innerHTML of a div to this html, so in jquery just one line of code in success event would populate the repeater control. This would be easier than returning a JSON collection from web service and then in success event of jquery ajax call you would need to create/populate html into the repeater control using DOM manipulation which would need some jquery.

Postback only Web Server Control

I have created a Composite Web Server Control which displays Image Thumbnails after a user selects files. This control uses
DataList ( to show Image Thumbnails)
RadUploadAsync ( To upload files)
For making the postback on RadUploadAsync I am making a false postback on a label.
function OnClientFileUploaded(sender, args) {
var contentType = args.get_fileInfo().ContentType;
//alert(contentType);
__doPostBack('lblSelectImage', 'radListView');
}
However when i add this control in a web page, this creates a complete postback of the page. Can someone tell me on how to avoid complete postback and keep it limited to Web Server Control only? Please note that this web server control is present inside
<asp:UpdatePanel ID="updatePanel1" runat="server">
<ContentTemplate>
<cc1:ImageControl ID="ImageControl1" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
Postbacks can be avoided by creating HTML Handler. For Rad Controls, telerik has given nice sample here.
http://demos.telerik.com/aspnet-ajax/asyncupload/examples/imageuploader/defaultcs.aspx

asp:button with no post back or refreshing the page

I have button in my page that when click on fires a jquery method that shows a div, but if the browser doesn't support javascript I want to fire a code behind method (using a postback). Is this possible? I'm already using this code but i can't see any results:
<asp:Button ID="Button1" runat="server" Text="Upload Files Here" Width="187px" onClick="CodeBehindMethod" OnClientClick="show_upload_box();return false"/>
and this is my jquery code:
function show_upload_box() {
$("#pop_up_background").css({
"opacity": "0.4"
});
$("#pop_up_background").fadeIn("slow");
$("#signup_pop_up_box").fadeIn('slow');
window.scroll(0, 0);
}
If the browser doesn't support JavaScript then your button would not work.
In ASP.NET, the runat="server" instruction is actually tied to a JavaScript method that submits a form (view page source to see that method).
Change or remove the value of that property to prevent the post back to your server.

Master page containing User Control with AutoCompleteExtender

Brief of Application:
I am creating a website which has a master page , a sub master page and some content pages.
I have created some user controls to display information on the main master page. I have registered those controls directly on my main master page and have specified their position.
I have used some content pages and other master page in ContentPlaceHolder.
Description:
I have a textbox on one of my user control, which i want to use with AutoCompleteExtender to help the user in finding the specific text by displaying him the related results.
Here is the sample piece of code:
<asp:TextBox ID="TxtSource" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender
ID="AutoCompleteSource"
TargetControlID = "TxtSource"
MinimumPrefixLength="1"
ServiceMethod="GetSourceList"
runat="server" UseContextKey="True">
</asp:AutoCompleteExtender>
Code Behind of Custom Control:
[System.Web.Services.WebMethod(), System.Web.Script.Services.ScriptMethod()]
public static string[] GetSourceList(string prefixText, int count, string contextKey)
{
string[] SourceList = {"Star Wars", "Star Trek", "Superman", "Memento", "Shrek", "Shrek II"};
return (from m in SourceList where m.StartsWith(prefixText.ToUpper()) select m).ToArray();
}
I am not using the webservice but the codebehind to call the method.
Issue:
The function in codebehind is never called.
I am aware of the fact that i have to keep the function in aspx file, but with my bad luck i am not adding the control on aspx file but on master file and master page is again treated as a control and not the page.
One solution :
I can add the custom control on every content page.
Problem :
1) No code re-usability, which i want to achieve.
2) Page layout will be changed.
Can there be any other solution, with least code changes?
Try to set the ServicePath of your autocomplete extender.
<asp:TextBox ID="TxtSource" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender
ID="AutoCompleteSource"
TargetControlID = "TxtSource"
MinimumPrefixLength="1"
ServiceMethod="GetSourceList"
ServicePath="yourpage.cs"
runat="server" UseContextKey="True">
</asp:AutoCompleteExtender>

Store innerhtml by jQuery in asp.net?

I have
<div id="ulAndil" runat="server">
</div>
and button
<asp:Button ID="btnAssignJudToCourse" runat="server" Text="تاكيد "
CssClass="button" CausesValidation="false"
OnClientClick="javascript:getShape();"
OnClick="btnAssignJudToCourse_Click" Visible="false" />
At runtime I create a lot of sortable html controls and then click confirm
I want to save inner html of this div before postback of button in session or anything
Using jQuery so when user click the button jQuery take inner html of div and stores it in cookie session any thing to store it after postback I can retrieve it
Please I want the exact code for this jQuery or javascript method and how to call on button
Why don't you put the generated HTML in a hidden field and postback.
Say getShape() is your javascript function
function getShape()
{
//your validations applied
document.getElementById('hdnHTML').value = document.getElementById('ulAndil').value;
return true;
}
where hdnHTML is the hidden element of HTML.

Categories