AutoComplete with service and Masterpage - asp.net

I've been struggling with getting all these components to work correctly, but when I get to the js it cannot find the TextBox control on the Student page.
The MasterPage ScriptManager:
<body>
<form id="MainForm" runat="server">
<asp:ScriptManager ID="ScriptManagerMain" runat="server">
<Services>
<asp:ServiceReference Path="~/AutoComplete.asmx" />
</Services>
</asp:ScriptManager>
Masterpage ContentPlaceHolder:
<asp:ContentPlaceHolder ID="ContentPlaceHolderStudent" runat="server">
</asp:ContentPlaceHolder>
Student (child) page:
<asp:Content ID="Content" ContentPlaceHolderID="ContentPlaceHolderStudent" runat="server" >
<asp:UpdatePanel ID="StudentSearchPanel" runat="server" ViewStateMode="Inherit">
<ContentTemplate>
Search by student ID:
<br />
<asp:TextBox ID="StudentIDSearchTextBox" runat="server" OnTextChanged="StudentIDSearchTextBox_TextChanged" Wrap="False" MaxLength="6" ClientIDMode="Static" ViewStateMode="Inherit"></asp:TextBox>
<br />
<asp:Label ID="StudentIDEntryError" runat="server" Visible="false" Font-Bold="True" ForeColor="Red" Text="Please enter a 6-digit student ID number."></asp:Label>
<br />
Or, begin typing student last name:
<br />
<asp:TextBox ID="StudentNameSearchTextBox" runat="server"
CssClass="StudentNameSearch"
ViewStateMode="Inherit"></asp:TextBox>
The Autocomplete Extender on the Student page:
<ajaxToolkit:AutoCompleteExtender ID="StudentNameSearchTextBox_AutoCompleteExtender" runat="server"
TargetControlID="StudentNameSearchTextBox"
ServicePath="~/Scripts/AutoComplete.asmx"
ServiceMethod="GetStudents"
OnClientItemSelected="onStudentSelected"
MinimumPrefixLength="2"
CompletionSetCount="30"
UseContextKey="True"
CompletionListCssClass="autocomplete_completionListElement"
CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
CompletionListItemCssClass="autocomplete_listItem" >
</ajaxToolkit:AutoCompleteExtender>
The AutoComplete.asmx is working, so I won't add that code. When I begin typing a student last name, I do get a json response, something like the following (altered to protect student data). I took this from FireBug:
{"d":["{\"First\":\"Lisaaa, Abby E.\",\"Second\":\"610999\"}","{\"First\":\"Lisbbb, Bobby P.\",\"Second\":\"151999\"}","{\"First\":\"Lisccc, Cathy M.\",\"Second\":\"739999\"}","{\"First\":\"Lisddd, David L.\",\"Second\":\"496999\"}","{\"First\":\"Liseee, Emily C.\",\"Second\":\"701999\"}","{\"First\":\"Lisfff, Frank G.\",\"Second\":\"623999\"}"]}
The problem, when I get to OnClientItemSelected="onStudentSelected" in GetStudentJson.js:
function onStudentSelected(sender, e) {
var selectedStudent = eval("(" + e._value + ")");
var StudentIdTextbox = document.getElementById('<%=ContentPlaceHolderStudent_StudentIDSearchTextBox.ClientID %>');
StudentIdTextbox.innerText = selectedStudent;
__doPostBack(StudentIdTextbox, "");
}
I get an error StudentIdTextbox is Null. I've tried adding all levels of placeholders by going to ViewSource to figure out how to find that box and give it the value of the student id, but to no avail. In fact, here is what it looks like:
<input name="ctl00$ContentPlaceHolderStudent$StudentIDSearchTextBox" type="text" maxlength="6" id="StudentIDSearchTextBox" />
Any advice??

I finally discovered that by problem lies in page lifecycle. Instead of referencing the script in the master page, I moved the script itself to the child page. Now, 'FindControl' is looking for a control that actually exists.
<script type="text/javascript">
function onStudentSelected(sender, e) {
var selectedStudent = eval("(" + e._value + ")");
var txtId = document.getElementById('<%= Page.Master.FindControl("ContentPlaceHolderStudent").FindControl("StudentSearchPanel").FindControl("StudentIDSearchTextBox").ClientID %>');
txtId.value = selectedStudent;
}
</script>
I was simply trying to find that control too soon.

Related

Master Page not working on ASP.NET Page

I'm having trouble with my ASP.NET Webform. All my pages are working perfectly with the master page, but for some reason my ProductItem page isn't accepting the master page.
Heres my code for ProductItem:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ProductItem.aspx.cs" Inherits="mumsBoutique.ProductItem" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<link href="Content/websiteStyle.css" rel="stylesheet" type="text/css" />
<h1><center>Product Details</center></h1>
<div class="row">
<asp:Label ID="productNameLabel" runat="server" Text="Product"></asp:Label>
<br />
<asp:Label ID="productItemNumber" runat="server" Text="ProductCode" CssClass="ProductItem_productNumber"></asp:Label>
</h3>
<h3>
<asp:Label ID="productCost" runat="server" Text="£0.00"></asp:Label>
</h3>
<p>
<asp:Image ID="productImage" runat="server" />
</p>
<h4>Product summary</h4>
<p>
<asp:Label ID="productDescription" runat="server" Text=""></asp:Label>
</p>
<!-- The right colum displays a text box for user to add items to the basket -->
<h3>Buy Item</h3>
<p>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" CssClass="text-danger" />
<p>
Quantity: <asp:TextBox ID="itemQuantity" runat="server" Text="1"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvItemQuantity" runat="server" ErrorMessage="Quantity is required" Text="Please specify the quantity required" ControlToValidate="itemQuantity" CssClass="text-danger" Display="Dynamic"></asp:RequiredFieldValidator>
<asp:CompareValidator ID="cvItemQuantity" runat="server" ErrorMessage="Invalid quantity value" Text="Please specify a valid numeric quantity value" ControlToValidate="itemQuantity" Type="Integer" Display="Dynamic" CssClass="text-danger" Operator="DataTypeCheck"></asp:CompareValidator>
<asp:RangeValidator ID="rvItemQuantity" runat="server" ErrorMessage="Invalid quantity value" Text="Please specify a quantity value between 1 and 10" ControlToValidate="itemQuantity" Type="Integer" MinimumValue="1" MaximumValue="10" Display="Dynamic" CssClass="text-danger"></asp:RangeValidator>
</p>
<p>
<asp:Button ID="btnAddToBasket" runat="server" Text="Add to basket" CssClass="btn btn-primary btn-lg" OnClick="btnAddToBasket_Click" />
</p>
</div>
</asp:Content>
But I don't think the problem is on this particular page. It seems the problem occurs when I run the page from the hyperlink on the Bags.aspx page
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Bags.aspx.cs" Inherits="mumsBoutique.Bags" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<link href="Content/mumsBoutique.css" rel="stylesheet" type="text/css" />
<h1><center>Bags</center></h1>
<div class="row">
<asp:DataList ID="DataList1" runat="server" CssClass="table ProductsDataList" DataKeyField="productID" DataSourceID="SqlDataSource1" RepeatColumns="4" RepeatDirection="Horizontal">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" Height="200px" Width="180px" ImageUrl='<%# Eval("Picture", "~/{0}") %>' />
<br />
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("productID", "ProductItem.aspx/{0}") %>' Text='<%# Eval ("productName") %>'></asp:HyperLink>
<br />
Item Number:
<asp:Label ID="ItemNumberLabel" runat="server" Text='<%# Eval("productNumber") %>' />
<br />
<asp:Label ID="CostLabel" runat="server" Text='<%# Eval("cost", "{0:C}") %>' />
<br />
<br />
<br />
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" SelectCommand="SELECT Items.productID, Items.productName, Items.productNumber, Items.picture, Items.cost, Items.categoryID, ItemCategories.Name AS Expr1 FROM ItemCategories INNER JOIN Items ON ItemCategories.categoryID = Items.categoryID WHERE (Items.categoryID = 2)"></asp:SqlDataSource>
</div>
</asp:Content>
Would really appreciate any help, been stuck for hours!
Update: Here are some screen shots of the problem I mean.
This is the Bags.aspx Page When you click on the hyperlink it takes you to the following
ProductItem.aspxAs can be seen the master page isn't being used for some reason. Yet in all other pages it works perfectly fine.
Here is the ProductItem.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.AspNet.FriendlyUrls;
using mumsBoutique.Models;
namespace mumsBoutique
{
public partial class ProductItem : System.Web.UI.Page
{
int _productID = 0;
protected void Page_Load(object sender, EventArgs e)
{
IList<string> segments = Request.GetFriendlyUrlSegments();
if (segments != null && segments.Count > 0)
{
// Convert the item ID to an integer and store it in the field _itemID
int.TryParse(segments[0], out _productID);
}
// If no item ID is specified, go back to the products page
if (_productID == 0)
{
Response.Redirect("Products");
}
// If _itemID is a valid value, search the database for the matching item
if (!IsPostBack && _productID > 0)
{
// open the connection to the database
using (ApplicationDbContext context = new ApplicationDbContext())
{
string sql = "SELECT * FROM Items WHERE productId = #productId";
System.Data.SqlClient.SqlParameter parameter = new System.Data.SqlClient.SqlParameter("#productId", _productID);
Item foundItem = context.Database.SqlQuery<Item>(sql, parameter).FirstOrDefault();
productNameLabel.Text = foundItem.productName;
productItemNumber.Text = foundItem.productNumber;
productCost.Text = foundItem.cost.ToString("c");
productImage.ImageUrl = "~/" + foundItem.picture;
productDescription.Text = foundItem.productDecription;
}
}
}
protected void btnAddToBasket_Click(object sender, EventArgs e)
{
// Check if page is valid
if (Page.IsValid)
{
int qty = 0;
// Get the quantity from the input field
qty = int.Parse(itemQuantity.Text);
// Check if item already exist in basket
OrderItem basketItem = ShopApp.Instance.GetBasketItem(_productID);
if (basketItem == null)
{
// item does not currently exist in basket, add new one
using (ApplicationDbContext context = new ApplicationDbContext())
{
// find the product item (pItem) with ItemId matching what is stored in the variable field (_itemId)
Item productItem = context.Items.FirstOrDefault(i => i.productID == _productID);
basketItem = new OrderItem()
{
productId = _productID,
Quantity = qty,
Price = double.Parse(productCost.Text, System.Globalization.NumberStyles.Currency),
Item = productItem
};
ShopApp.Instance.BasketItems.Add(basketItem);
}
}
else
{
// item already exists in basket, increase the quantity
basketItem.Quantity += qty;
}
((SiteMaster)Master).UpdateBasket();
}
}
}
}
It looks like you are trying to pass the productID as a parameter, so try changing NavigateUrl='<%# Eval("productID", "ProductItem.aspx/{0}") %>'
to
NavigateUrl='<%# Eval("productID", "ProductItem.aspx?productID={0}") %>'
Also, you need to move your CSS links to the appropriate place in your master page - you should not be linking to CSS style sheets from within a page when using a master page, and certainly not from within a ContentPlaceHolder section as you are not overriding any styles. This is more than likely the cause of your problem.
UPDATE
I've taken a look at your project and found the following problems, just by eyeballing it (can't run it due to diff DB version, etc):
The markup in your master page is badly formed. You are basically doing everything in the head section because you have no body section.
The link to your style sheet in the master page is outside of the
HTML document - it should be within the head section. Here is how structure of your master page should look:
<%# Master Language="C#" AutoEventWireup="true"
CodeBehind="Site.master.cs" Inherits="mumsBoutique.SiteMaster" %>
<!DOCTYPE html>
<html lang="en">
<head runat="server">
<meta charset="utf-8" />
<link href="Content/websiteStyle.css" rel="stylesheet"
type="text/css" />
</head>
<body>
<form id="form1" runat="server">
...
</form>
</body>
Remove the superfluous CSS links from your Bags and ProductItem
pages - when you have fixed the CSS link in the master page, that is
all you should need; you're obviously not overriding anything as you are specifying the same style sheet throughout.

get info from one page and show it on other page

i m working on shopping cart site
i want to show complete information of a product contained in a div section. on an other page. i have may div that contained information.
goal is to get the info on a new page when user clicks some product's image.
Error:
Control 'MainContent_ImageButton1' of type 'ImageButton' must be placed inside a form tag with runat=server.
HTML:
<div id="physics" runat="server">
<h3>High School Physics</h3>
<%-- <img src="images/Book.jpg" /> --%>
<asp:ImageButton ID="ImageButton1"
src="images/Book.jpg" runat="server" onclick="ImageButton1_Click" />
<p> Book Description Goes Here
<br />
<asp:Label ID="Label1" runat="server" Text="Label">PKR 770/-</asp:Label>
<br />
<asp:TextBox ID="TextBox1" Text="1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Add" />
</p>
</div>
Code :
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
StringWriter sw = new StringWriter();
HtmlTextWriter w = new HtmlTextWriter(sw);
physics.RenderControl(w);
Session["mySessionVar"] = sw.GetStringBuilder().ToString();
Response.Redirect("ShowLarge.aspx", true);
}
HTML: where i want to show this info
<div id="ShowInLargeView" runat="server">
</div>
Code:
protected void Page_Load(object sender, EventArgs e)
{
ShowInLargeView.InnerHtml = (String)Session["mySessionVar"];
}
i want to show the complete info of Div in an other page. i m getting an error. this scenario is about shopping cart
i need help
please help.
The error you are getting is related to the fact that you are trying to add an event handler
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
In order to add an event handler to an element on your page it will need to be encapsulated in a 'form' with the runat="server" attribute. this will result in the click event of the ImageButton ending up in your code-behind.
so your aspx would become something like :
<form runat="server">
<div id="physics" runat="server">
<h3>High School Physics</h3>
<%-- <img src="images/Book.jpg" /> --%>
<asp:ImageButton ID="ImageButton1"
src="images/Book.jpg" runat="server" onclick="ImageButton1_Click" />
<p> Book Description Goes Here
<br />
<asp:Label ID="Label1" runat="server" Text="Label">PKR 770/-</asp:Label>
<br />
<asp:TextBox ID="TextBox1" Text="1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Add" />
</p>
</div>
</form>
In general it should suffice to encapsulate your entire page in a form tag, this way all events will be passed to your code-behind.

asp.net ajax like reorder list

I'm trying to create a draggable list to change the order some pictures are displayed in a product page. I wan't to be able to do this in the product edit page (same place where I add the pics and their description). So, when creating I have nothing inserted on the database and since the AJAX toolkit reorderlist only works with a datasource I was specifying the list as the source of the reorderlist and calling the databind method. In the item template of the reorder list I have a textbox to edit the pic description and a img that displays the photo. I can drag the items and the list gets reordered, however when I click save I can't get the updated text on the textbox and the order property on the picture doesn't get updated. I've tried manually getting the items in the reorderlist but they're always null even though the list shows 20 items the DataItem is empty. I've enabled viewstate and didn't help either.
Here's my code:
<ajaxToolkit:ReorderList ID="rdlPhotos" runat="server" SortOrderField="PhotoOrder" AllowReorder="true" PostBackOnReorder="true" ClientIDMode="AutoID" EnableViewState="true" ViewStateMode="Enabled">
<ItemTemplate>
<div>
<%--<eva:PhotoView ID="iPV" runat="server" Photo='<%# Container.DataItem %>' />--%>
<asp:Image ID="imgPhoto" runat="server" ImageUrl='<%# string.Format("http://eva-atelier.net/sparkle{0}", Eval("Path").ToString().Substring(1)) %>' Width="150" Height="150" />
<div class="formGrid">
<label class="formLabel">Title</label>
<asp:TextBox ID="txtTitle" runat="server" Text='<%#Bind("FileTitle") %>' />
<br />
<label class="formLabel">Description</label>
<asp:TextBox ID="txtDescription" runat="server" Text='<%#Bind("FileDescription") %>' />
<br />
</div>
<p>
<asp:Button ID="btnRemove" runat="server" Text="Remover" />
</p>
</div>
</ItemTemplate>
<ReorderTemplate>
<asp:Panel ID="pnlReorder" runat="server" />
</ReorderTemplate>
<DragHandleTemplate>
<div style="width:20px;height:20px;background-color:Red"></div>
</DragHandleTemplate>
</ajaxToolkit:ReorderList>
And below the C# code:
private void AddPhotosView()
{
if (_currentProduct.Photos != null && _currentProduct.Photos.Count > 0)
{
rdlPhotos.DataSource = _currentProduct.Photos;
rdlPhotos.DataBind();
}
}
I'm new to Asp.net I come from a large WPF background, sorry if I'm making basic question :)
Thanks
For updating order of ReorderList items add your handler for it's OnItemReorder event. In this case your handler may looks like this:
protected void ReorderHandler(object sender, ReorderListItemReorderEventArgs e)
{
var movedPhoto = _currentProduct.Photos[e.OldIndex];
_currentProduct.Photos.RemoveAt(e.OldIndex);
_currentProduct.Photos.Insert(e.NewIndex, movedPhoto);
_currentProduct.Photos.Save();
}
For updating FileTitle and FileDescription of single Photo it is easy to use OnUpdateCommand event of ReorderList and a button with attribute CommandName="Update" for each Photo.
And for updating all Photos at once just iterate through rdlPhotos.Items in next manner:
protected void SaveAllHandler(object sender, EventArgs e)
{
foreach (var riItem in rdlPhotos.Items)
{
var id = ((HiddenField)riItem.FindControl("itemID")).Value;
var title = ((TextBox)riItem.FindControl("txtTitle")).Text;
var description = ((TextBox)riItem.FindControl("txtDescription")).Text;
UpdatePhoto(id, title, description);
}
}
Remember that rdlPhotos.Items here are in initial order. And for identifying which Photo should be updated add hidden field with Photo.ID-value to ReorderList's ItemTemplate like this:
<asp:HiddenField runat="server" ID="itemID" Value='<%# Eval("ID") %>' />

Update Panel animation extender with multi update panel

Q:
I use Update Panel animation extender
,, it works so good but unfortunately
,,when i have more than update panel
on the same page and any partial post
back for any update panel on the page
the extender works (animate)..
How to make the extender works with
the intended one (the one i add the
extender to Only)..please sample if possible
The Script:
<script type="text/javascript" language="javascript">
function onUpdating() {
// get the update progress div
var updateProgressDiv = $get('updateProgressDiv');
// make it visible
updateProgressDiv.style.display = '';
// get the gridview element
var gridView = $get('<%=this.pnl_courseImg.ClientID %>');
// get the bounds of both the gridview and the progress div
var gridViewBounds = Sys.UI.DomElement.getBounds(gridView);
var updateProgressDivBounds = Sys.UI.DomElement.getBounds(updateProgressDiv);
// do the math to figure out where to position the element (the center of the gridview)
var x = gridViewBounds.x + Math.round(gridViewBounds.width / 2) - Math.round(updateProgressDivBounds.width / 2);
var y = gridViewBounds.y + Math.round(gridViewBounds.height / 2) - Math.round(updateProgressDivBounds.height / 2);
// set the progress element to this position
Sys.UI.DomElement.setLocation(updateProgressDiv, x, y);
}
function onUpdated() {
// get the update progress div
var updateProgressDiv = $get('updateProgressDiv');
// make it invisible
updateProgressDiv.style.display = 'none';
}
</script>
My ASPX:
<asp:Panel ID="pnl_courseImg" runat="server" HorizontalAlign="Center">
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<contenttemplate>
<br />
<asp:ListView ID="lv_showCourseImages" runat="server" ItemPlaceholderID="a"
onitemcommand="lv_showCourseImages_ItemCommand">
<LayoutTemplate>
<table ID="Table1" runat="server" cellpadding="2" cellspacing="2"
>
<tr ID="a" runat="server">
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr ID="Tr1" runat="server">
<td>
<asp:Image ID="img_news" runat="server" ImageUrl='<%# "CourseImages" + "/" + Eval("FK_CourseCode") + "/"+ Eval("photoName")%>' BorderWidth="4px" Height="355px"
Width="410px"/>
</td>
</tr>
<tr id = "tr2" runat ="server">
<td>
<asp:HiddenField ID="hf_newsImage" runat="server" Value ='<%#Eval("photoId")%>'/>
<asp:Button ID="btn_deleteImg" runat="server" Text="Delete" CommandName ="deleteImage" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<asp:DataPager ID="dp_CourseImages" runat="server"
PagedControlID="lv_showCourseImages"
PageSize="1" onprerender="dp_CourseImages_PreRender">
<Fields>
<asp:NextPreviousPagerField ButtonType="Button" NextPageText=">>"
PreviousPageText="<<" ShowFirstPageButton="True"
ShowLastPageButton="True" />
</Fields>
</asp:DataPager>
</contenttemplate>
</asp:UpdatePanel>
<cc3:updatepanelanimationextender id="UpdatePanel2_UpdatePanelAnimationExtender"
runat="server" enabled="True" behaviorid="animation" targetcontrolid="UpdatePanel2">
<Animations>
<OnUpdating>
<Parallel duration="0">
<%-- place the update progress div over the gridview control --%>
<ScriptAction Script="onUpdating();" />
<%-- disable the search button --%>
<EnableAction AnimationTarget="btn_deleteImg" Enabled="false" />
<%-- fade-out the GridView --%>
<FadeOut minimumOpacity=".5" />
</Parallel>
</OnUpdating>
<OnUpdated>
<Parallel duration="0">
<%-- fade back in the GridView --%>
<FadeIn minimumOpacity=".5" />
<%-- re-enable the search button --%>
<EnableAction AnimationTarget="btn_deleteImg" Enabled="true" />
<%--find the update progress div and place it over the gridview control--%>
<ScriptAction Script="onUpdated();" />
</Parallel>
</OnUpdated>
</Animations>
</cc3:updatepanelanimationextender>
</asp:Panel>
i have one more update panel when click the button in it it fires the extender in this update panel how to fix this problem.
Thanks in advance..
Stolen from the ASP.NET Forums (sorry, didn't know how to get a link directly to the specified thread post):
Okay I solved it. here is my solution:
Just add the following javascript to your page
<script type="text/javascript">
var currentPostBackElement;
function pageLoad()
{
var manager = Sys.WebForms.PageRequestManager.getInstance();
manager.add_initializeRequest(OnInitializeRequest);
}
function OnInitializeRequest(sender, args)
{
var manager = Sys.WebForms.PageRequestManager.getInstance();
currentPostBackElement = args.get_postBackElement().parentElement;
}
</script>
and use the ConditionScript in the UpdatePanelAnimationExtender as followed:
<ajaxToolkit:UpdatePanelAnimationExtender ID="MyExtender" runat="server" TargetControlID="updPanel">
<Animations>
<OnUpdating>
<Condition ConditionScript="currentPostBackElement.name == 'updPanel' ">
<FadeOut AnimationTarget="updPanel" minimumOpacity=".1" Fps="30" />
</Condition>
</OnUpdating>
<OnUpdated>
<Condition ConditionScript="currentPostBackElement.name == 'updPanel' ">
<FadeIn AnimationTarget="updPanel" minimumOpacity=".1" Fps="30" />
</Condition>
</OnUpdated>
</Animations>
</ajaxToolkit:UpdatePanelAnimationExtender>
Its important to have the trigger (in my case a timer) in the update panel which should be refreshed. so you can get the parent
I didn't test this solution by I hope it will help you.
The Ajax Control Toolkit is now maintained by DevExpress, and this bug has been resolved. I updated my DLL to version 18.1, and I'm no longer experiencing the problem.

ModalPopupExtender and validation problems

The problem I am facing is that when there is validation on a page and I am trying to display a model pop-up, the pop-up is not getting displayed. And by using fire-bug I have noticed that an error is being thrown.
The button that is used to display the pop-up has cause validation set to false so I am stuck as to what is causing the error.
I have created a sample page to isolate the problem that I am having, any help would be greatly appreciated.
The Error
function () {Array.remove(Page_ValidationSummaries, document.getElementById("ValidationSummary1"));}(function () {var fn = function () {AjaxControlToolkit.ModalPopupBehavior.invokeViaServer("mpeSelectClient", true);Sys.Application.remove_load(fn);};Sys.Application.add_load(fn);}) is not a function
http://localhost:1131/WebForm1.aspx
Line 136
ASP
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="CLIck10.WebForm1" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:Button ID="btnPush" runat="server" Text="Push" CausesValidation="false" onclick="btnPush_Click" />
<asp:TextBox ID="txtVal" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtVal" ErrorMessage="RequiredFieldValidator" />
<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
<asp:Panel ID="pnlSelectClient" Style="display: none" CssClass="box" runat="server">
<asp:UpdatePanel ID="upnlSelectClient" runat="server">
<ContentTemplate>
<asp:Button ID="btnOK" runat="server" UseSubmitBehavior="true" Text="OK" CausesValidation="false" OnClick="btnOK_Click" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" CausesValidation="false" OnClick="btnCancel_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
<input id="popupDummy" runat="server" style="display:none" />
<ajaxToolkit:ModalPopupExtender ID="mpeSelectClient" runat="server"
TargetControlID="popupDummy"
PopupControlID="pnlSelectClient"
OkControlID="popupDummy"
BackgroundCssClass="modalBackground"
CancelControlID="btnCancel"
DropShadow="true" />
</div>
</form>
Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CLIck10
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnOK_Click(object sender, EventArgs e)
{
mpeSelectClient.Hide();
}
protected void btnCancel_Click(object sender, EventArgs e)
{
mpeSelectClient.Hide();
}
protected void btnPush_Click(object sender, EventArgs e)
{
mpeSelectClient.Show();
}
}
}
This is an issue with using both ValidationSummary and ModalPopup.
see here: http://ajaxcontroltoolkit.codeplex.com/WorkItem/View.aspx?WorkItemId=12835
The problem is that there is a missing ";" between the two injected scripts.
Their solution is to create/use a custom server control that inherits from ValidationSummary, that injects a ";" into the page startup script to fix the bug:
[ToolboxData("")]
public class AjaxValidationSummary : ValidationSummary
{
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), this.ClientID, ";", true);
}
}
Try setting your ValidationSummary "Enabled" property to false on this event : "btnPush_Click"
; and then setting it back to enabled = "true" on this events : "btnOK_Click" ,"btnCancel_Click".
I think this will work if you do not have the validation summary inside the Panel that you want to pop up.But it is not a solution if you need the validation summary inside the pop up panel,...witch is my case :(.
Best Regards.
I tried all the available answer online but didn't worked any. Then i tried to move my modal popup extender at very end of the HTML and it works fine for me. Me and my users are Happy :)
I am not using FROM tag I am using Content place holder just like below:
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<table id="tblMessage" runat="server" width="100%" >
<tr align="center">
<td align="center">
main content and
<asp:Panel ID="pnlSelectClient" Style="display: none" CssClass="box" runat="server">
<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
<asp:UpdatePanel ID="upnlSelectClient" runat="server">
<ContentTemplate>
<asp:Button ID="btnOK" runat="server" UseSubmitBehavior="true" Text="OK" CausesValidation="false" OnClick="btnOK_Click" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" CausesValidation="false" OnClick="btnCancel_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
If you notice i have validation summary inside the panel because i want error message inside the pop up(i have some additional control in pop up too). and
Some more HTML tag here as i have so many other things to do in one page. right before closing tag of TABLE
<ajaxToolkit:ModalPopupExtender ID="mpeSelectClient" runat="server"
TargetControlID="popupDummy"
PopupControlID="pnlSelectClient"
OkControlID="popupDummy"
BackgroundCssClass="modalBackground"
CancelControlID="btnCancel"
DropShadow="true" />
</table>
Done.it's working. Hope that works for other too.
Are you using validation groups anywhere on the page? I've had problems with control events not firing when they are not part of a validation group and other controls on the page are part of a validation group.
I'd try changing this:
<input id="popupDummy" runat="server" style="display:none" />
to something like this:
<asp:Button id="popupDummy" runat="server" CausesValidation="false" Visible="false" />
I bet the untyped input is requiring validation.
i had the same issue, adding ValidationGroup to the validation controls did the trick!
One other thing to try, if you don't need Client Script you can disable it in the markup. Doing that fixed our problem.
EnableClientScript="false"

Resources