updatepanel does not trigger repeater itemcommand - updatepanel

I just want to trigger the LinkButton in a repeater which has a OnItemCommand. But the page do post back. Here is my code:
<asp:UpdatePanel ID="recommendedAdvertsUpPnl" runat="server">
<ContentTemplate>
<div class="tagList">
<asp:Label ID="lbListBookType" runat="server"></asp:Label>
<asp:Repeater ID="rpRecommendedAdvertFacultyList" runat="server" OnItemDataBound="rpRecommendedAdvertFacultyList_ItemDataBound" OnItemCommand="rpRecommendedAdvertFacultyList_ItemCommand">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<asp:LinkButton ID="lbtnAdvertFaculty" runat="server" CommandArgument='<%#Eval("facultyId") %>' CommandName="selectFaculty" CssClass="advertFacultySelection"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate></FooterTemplate>
</asp:Repeater>
</div>
<div class="RecommendedAdverts_List">
<asp:Repeater ID="rpRecommendedAdvertList" runat="server" OnItemDataBound="rpRecommendedAdvertList_ItemDataBound">
<HeaderTemplate>
<ul class="content_recommended">
</HeaderTemplate>
<ItemTemplate>
<%# Container.ItemIndex % 4 == 0 ? "<li><div class=advertContainer>": String.Empty%>
<div class="advertPanel">
<div class="rAdvPanel">
<div class="advertPic"><asp:Panel ID="pnlRecAdvertPic" runat="server"></asp:Panel></div>
<div class="advertInfoPanel">
<%#Eval("Book.Name")%> <br />
<%#Eval("Book.Authors")%><br />
<%#Eval("Price")%> TL<br />
</div>
</div>
</div>
<%# Container.ItemIndex % 4 == 3 ? "</div></li>": String.Empty%>
</ItemTemplate>
<FooterTemplate>
</div></li>
</ul>
</FooterTemplate>
</asp:Repeater>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="rpRecommendedAdvertFacultyList" EventName="ItemCommand" />
</Triggers>
</asp:UpdatePanel>
There is no problem except for triggering. Here is the my server side code:
protected void rpRecommendedAdvertFacultyList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
AdvertFacultyInfo item = (AdvertFacultyInfo)e.Item.DataItem;
LinkButton lbtnAdvertFaculty = (LinkButton)e.Item.FindControl("lbtnAdvertFaculty");
lbtnAdvertFaculty.Text = item.Faculty.name;
}
}
protected void rpRecommendedAdvertFacultyList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
switch (e.CommandName)
{
case "selectFaculty":
List<AdvertFacultyInfo> advFacultyInfoList = EntitiyProvider.GetAdvertFacultyInfoListByFacultyId(Convert.ToInt32(e.CommandArgument));
List<Advert> selectedList = new List<Advert>();
foreach (AdvertFacultyInfo item in advFacultyInfoList)
{
Advert currentAdv = this.recommendedAdvertList.FirstOrDefault(i => i.id == item.advertId);
if ( currentAdv != null)
{
selectedList.Add(currentAdv);
}
}
rpRecommendedAdvertList.DataSource = selectedList;
rpRecommendedAdvertList.DataBind();
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "temp", "<script type='text/javascript'>$('.content_recommended').quickPager()</script>", false);
break;
default:
break;
}
}
I have also tried this code: But it gives error like lbtnAdvertFaculty could'nt find
<asp:AsyncPostBackTrigger ControlID="lbtnAdvertFaculty" EventName="Click" />
I have researched a lot of document written about this problem but I could not find useful examples and solution.
Best Regards.

try putting ClientIDMode="AutoID" to #page directive

Related

VB.net OnClientClick pass in ID of another div

I have the following asp repeater:
<asp:Repeater runat="server" ID="rptResults">
<ItemTemplate>
<div class="FileFile Large pdf SearchResult" id="<%# DirectCast(Container.DataItem, FileFolder).DocStoreID%>">
<a href='<%# DirectCast(Container.DataItem, FileFolder).Link %>' style="text-decoration:none">
<%# DirectCast(Container.DataItem, FileFolder).BackgroundHTML%>
<p style="float:left;line-height:32px;margin:0px"><%# DirectCast(Container.DataItem, FileFolder).Filename%></p>
</a>
<asp:Button runat="server" OnClientClick="return confirmation(this);" ID="btnDeleteFile" CommandArgument="<%# DirectCast(Container.DataItem, FileFolder).DocStoreID%>" UseSubmitBehavior="false" Text="Delete" Style="float:right;margin-top:8px;cursor:pointer;"/>
<a style="float:right;line-height:32px;margin-right:10px">ID = <%# DirectCast(Container.DataItem, FileFolder).DocStoreID%></a>
</div>
</ItemTemplate>
</asp:Repeater>
<script>
function confirmation(sender) {
if (confirm("Delete file "+ sender.id + "?"))
return true;
else return false;
}
</script>
I want the OnClientClick to say:
Delete File ######
to do this I need to pass in the id of the parent div, or the content of the <a> next to it.
Currently, I have OnClientClick="return confirmation(this);", which passes in the button. SO I could possibly store this information in a field on the button, but I have tried:
name="%# DirectCast(Container.DataItem, FileFolder).DocStoreID%>"
But this does not work. Are there any other variables I can use to store this, or a way to pass a reference to another element within the repeater?
you can use title attribute in your button:
title="<%# DirectCast(Container.DataItem, FileFolder).DocStoreID%>"
and then your javascript will be
function confirmation(sender){
if(confirm("Delete file " + sender.title + " ?"))
return true;
else
return false;
}
be aware that title attribute is intended to display a tooltip, so the user will see a toolip over your button. Hope it helps.
Try this
OnClientClick="return confirmation('<%= DirectCast(Container.DataItem, FileFolder).DocStoreID %>');"
And you JS would be
function confirmation(sender) {
if (confirm("Delete file "+ sender + "?"))
return true;
else return false;
}

ASP.Net My Updated Value From Drop Down List Doesn't Update/Display

I have a 4 page ASP.NET form which is storing data in the session. A button on my 3rd page clears the session. All this is working fine but I'm having a problem updating a value on my confirmation page as it retains/displays my initial selected value and i cant figure out why.
1st Page HTML With DropDownList
<asp:DropDownList ID="ddlInnoc" runat="server" class="form-control">
<asp:ListItem Value="0">- - Please Select - -</asp:ListItem>
<asp:ListItem Value="Male">Male</asp:ListItem>
<asp:ListItem Value="Female">Female</asp:ListItem>
</asp:DropDownList>
1st Page Code Behind Which Re-displays Selected Value
protected void Page_Load(object sender, EventArgs e)
{
txtData1.Focus();
if (txtData1.Text == string.Empty && Session["pg1input"] != null)
{
txtData1.Text = Session["pg1input"].ToString();
}
if (Session["pg1dd"] != null)
{
ddlInnoc.SelectedValue = Session["pg1dd"].ToString();
}
//if (Session["pg1dd"].ToString() == "")
//{
// ddlInnoc.SelectedValue = Session["pg1dd"].ToString();
//}
}
protected void pg1button_Click(object sender, EventArgs e)
{
Session["pg1input"] = txtData1.Text;
Session["pg1dd"] = ddlInnoc.SelectedItem;
Response.Redirect("/Session/pg2.aspx");
}
Page 3 HTML Code
<div class="form-group">
<div class="col-xs-12">
<asp:Label ID="Label1" class="col-md-2 control-label" runat="server" Text="Name:"></asp:Label>
<div class="col-md-3 form-control-static">
<%=Session["pg1input"] %>
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<asp:Label ID="Label2" class="col-md-2 control-label" runat="server" Text="Sex:"></asp:Label>
<div class="col-md-3 form-control-static">
<%=Session["pg1dd"] %>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-offset-4 col-xs-12">
<asp:LinkButton ID="pg1EditButton" runat="server" OnClick="pg1EditButton_Click" CssClass="btn btn-default">
<span aria-hidden="true" class="glyphicon glyphicon-pencil"></span> Edit
</asp:LinkButton>
</div>
</div>
Page 3 Edit Button Code Behind
protected void pg1EditButton_Click(object sender, EventArgs e)
{
Response.Redirect("/Session/pg1.aspx");
}
I suspect that its something to do with the code behind on my page 1 as all the other fields/radio buttons on the other pages retrieves and displays the updated value on my 3rd page.
You are setting it back to the value in your session on postback.
Add this to your Page_Load.
if (!IsPostBack)
{
//set values from session
}
Fix is
if (!IsPostBack)
{
if (ddlInnoc.SelectedValue != "0" && Session["pg1dd"] != null)
{
ddlInnoc.SelectedValue = Session["pg1dd"].ToString();
}
}

Validate dynamically created fields when one is changed

I have a program that dynamically creates various text boxes / drop down lists. I am trying to figure out how to validate these fields only when one is changed. Basically if someone entered a date in the text box then I need the program to validate that the drop down list was changed or vice versa. If there are no changes to both fields then it should not validate. Any help would be extremely appreciated. Here is the code:
<asp:TemplateField HeaderText="ValidatedDate" SortExpression="ValidatedDate">
<EditItemTemplate>
<asp:TextBox ID="txtValDate" Width="100px" MaxLength="10" runat="server" AutoPostBack="true"
Text='<%# Bind("ValidatedDate","{0:MM/dd/yyyy}") %>'></asp:TextBox>
<asp:RegularExpressionValidator ValidationGroup="g1" ID="RegularExpressionValidator10"
runat="server" ControlToValidate="txtValDate" Display="None" ErrorMessage="Validated Date: ##/##/####"
ValidationExpression="\d{1,2}/\d{1,2}/\d{4}"></asp:RegularExpressionValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblValidatedDate" runat="server" Text='<%# Bind("ValidatedDate","{0:MM/dd/yyyy}")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProductStatus" SortExpression="ProductStatusDescription">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList4" runat="server" DataSourceID="SqlDataSource6" AutoPostBack="true"
DataTextField="StatusDescription" DataValueField="StatusID" SelectedValue='<%# Bind("Status") %>'>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblProductStatus" runat="server" Text='<%# Bind("ProductStatusDescription")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
My apologies, the code can be a bit confusing without the correct context.
ebyrob, thank you for your help. I figured it out however and it works beautifully. Here is the code that fixed it all:
protected void AddError(string errorMessage)
{
cstValidate.IsValid = false;
cstValidate.ErrorMessage = errorMessage;
cstValidate.EnableClientScript = false;
}
protected void GridView2_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtValidatedDate = GridView2.Rows[e.RowIndex].FindControl("txtValDate") as TextBox;
DropDownList ddlStatusCompare = GridView2.Rows[e.RowIndex].FindControl("dropdownlist4") as DropDownList;
if (txtValidatedDate.Text == string.Empty && ddlStatusCompare.SelectedValue == "1")
{
AddError("Please enter a Validated Date");
e.Cancel = true;
}
else if (txtValidatedDate.Text != string.Empty && ddlStatusCompare.SelectedValue == "0"
|| txtValidatedDate.Text != string.Empty && ddlStatusCompare.SelectedValue == "99")
{
AddError("Please remove the Validated Date");
e.Cancel = true;
}
if (!e.Cancel)
Helpers.LogChanges(GridView2, e, _employeeID, "SaleProducts");
}

Partial page updating using update panel

I am creating "edit my profile page" where I have some text boxes and drop down lists.I have a requirement such that when I select a value in my first drop down, the second drop down should fill. But this is not happening.
<asp:UpdatePanel runat="server" ID="updatepanel1" UpdateMode="Conditional">
<ContentTemplate >
<asp:Label runat="server" Id="lbljobIndus" Text="Preferred Job Industry" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<span style="color: black; font-family: Calibri; font-size: small">:</span>
<asp:Label runat="server" ID="lblPreferredJobIndustry" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<asp:DropDownList ID="tbPreferredJobIndustry" runat="server" Height="19px" OnSelectedIndexChanged="ddlTargetedIndustry_SelectedIndexChanged">
<asp:ListItem Selected="True" Value="-1">--Select Industry--</asp:ListItem>
<asp:ListItem Value="1">Administration</asp:ListItem>
<asp:ListItem Value="2">Hospital/HealthCare</asp:ListItem>
<asp:ListItem Value="3">Medical Transcription</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<br />
<asp:Label runat="server" ID="lblJobCat" Text="Preferred Job Category" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<span style="color: black; font-family: Calibri; font-size: small">:</span>
<asp:Label runat="server" ID="lblJobCategory" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<asp:DropDownList ID="tbJobCategory" runat="server">
<asp:ListItem Selected="True" Value="-1">-Position Category-</asp:ListItem>
</asp:DropDownList>
<br />
<br />
</ContentTemplate>
</asp:UpdatePanel>
This is the code to populate the second drop down list :-
protected void ddlTargetedIndustry_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet ds = new DataSet();
SqlDataAdapter myda = new SqlDataAdapter("Select s_CategoryName,FK_TargetedIndustryID FROM [OfinityJobSearch].[dbo].[tm_JobCategory] where FK_TargetedIndustryID='" + tbPreferredJobIndustry.SelectedItem.Value + "'", con);
myda.Fill(ds);
tbJobCategory.DataSource = ds;
tbJobCategory.DataValueField = "FK_TargetedIndustryID";
tbJobCategory.DataTextField = "s_CategoryName";
tbJobCategory.DataBind();
tbJobCategory.Items.Insert(0, new ListItem("--Select Job Category--", "0"));
}
I used update panel so that the values in other text boxes will not get cleared on the post back. But right now, I think the post back is not happening.Can you please check my code and tell me where the error is?
Set AutoPostBack= true for the first ddl
U can use AjaxToolkit CascadingDropDown it's very helpful and useful. But in case of CascadingDropDown u need additional service.
<ajaxToolkit:CascadingDropDown ID="CDD1" runat="server"
TargetControlID="DropDownList2"
Category="Model"
PromptText="Please select a model"
LoadingText="[Loading models...]"
ServicePath="CarsService.asmx"
ServiceMethod="GetDropDownContents"
ParentControlID="DropDownList1"
SelectedValue="SomeValue" />
UPDATE:
Full example here
your *.aspx
<asp:DropDownList ID="DropDownList1" runat="server" Width="170" />
<asp:DropDownList ID="DropDownList2" runat="server" Width="170" />
<ajaxToolkit:CascadingDropDown ID="CascadingDropDown1" runat="server" TargetControlID="DropDownList1"
Category="Make" PromptText="Please select a make" LoadingText="[Loading makes...]"
ServicePath="CarsService.asmx" ServiceMethod="GetDropDownContents" />
and add code to page
[WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static CascadingDropDownNameValue[] GetDropDownContentsPageMethod(string knownCategoryValues, string category)
{
return new CarsService().GetDropDownContents(knownCategoryValues, category);
}
add web service
<%# WebService
Language="C#"
CodeBehind="~/App_Code/CarsService.cs"
Class="CarsService" %>
Code for service
[System.Web.Script.Services.ScriptService]
public class CarsService : WebService
{
// Member variables
private static XmlDocument _document;
private static Regex _inputValidationRegex;
private static object _lock = new object();
// we make these public statics just so we can call them from externally for the
// page method call
public static XmlDocument Document
{
get
{
lock (_lock)
{
if (_document == null)
{
// Read XML data from disk
_document = new XmlDocument();
_document.Load(HttpContext.Current.Server.MapPath("~/App_Data/CarsService.xml"));
}
}
return _document;
}
}
public static string[] Hierarchy
{
get { return new string[] { "make", "model" }; }
}
public static Regex InputValidationRegex
{
get
{
lock (_lock)
{
if (null == _inputValidationRegex)
{
_inputValidationRegex = new Regex("^[0-9a-zA-Z \\(\\)]*$");
}
}
return _inputValidationRegex;
}
}
/// <summary>
/// Helper web service method
/// </summary>
/// <param name="knownCategoryValues">private storage format string</param>
/// <param name="category">category of DropDownList to populate</param>
/// <returns>list of content items</returns>
[WebMethod]
public AjaxControlToolkit.CascadingDropDownNameValue[] GetDropDownContents(string knownCategoryValues, string category)
{
// Get a dictionary of known category/value pairs
StringDictionary knownCategoryValuesDictionary = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
// Perform a simple query against the data document
return AjaxControlToolkit.CascadingDropDown.QuerySimpleCascadingDropDownDocument(Document, Hierarchy, knownCategoryValuesDictionary, category, InputValidationRegex);
}

required field validator not working with html editor

I have a text box using cc1:Editor and when I place a required field validator on it, it displays as soon as the page loads. How can I hide the error and allow it to display only if the html editor box is empty?
<code><cc1:Editor ID="txtDescription" Width="500px" Height="525px"
runat="server" TextMode="SingleLine" /></code>
<code>
<asp:RequiredFieldValidator ID="rfvDescription" runat="server"
ControlToValidate="txtDescription"
ErrorMessage="Must include Description" Font-Bold="True"></asp:RequiredFieldValidator>
</code>
<code><asp:Button ID="SubmitBtn" runat="server"
Text="Submit" OnClick="SubmitBtn_Click" class="form-td" Height="30px" />
<script language="javascript" type="text/javascript">
document.onkeypress = keyhandler;
function keyhandler(e) {
Key = window.event.keyCode; if (Key == 13) {
var obj = document.getElementById('<%=SubmitBtn.ClientID%>');
obj.focus();
obj.click();
}
}
</script>
Yes, you can perform custom validation on your submit button client side & server side validation on your postback event thus removing required field validator. Check following example:
On your aspx page
<p>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="javascript:return ValidateEditor();"
ValidationGroup="myGroup" onclick="Button1_Click" />
<br />
</p>
<asp:Label ID="lblMessage" runat="server" ForeColor="Red"></asp:Label>
<cc1:Editor ID="Editor1" runat="server" />
<script type="text/javascript">
function ValidateEditor() {
var txtEditor = $find('<%=Editor1.ClientID %>');
if (txtEditor.get_content() == null || txtEditor.get_content() == '') {
alert('Text cannot be empty');
document.getElementById('<%=lblMessage.ClientID %>').innerHTML='Text cannot be empty';
return false;
}
else
return true;
}
</script>
On server side
if (string.IsNullOrEmpty(Editor1.Content.ToString()))
{
lblMessage.Text = "Text cannot be empty";
}
else
{
// Do your work here
}