ValidationSummary in MasterPage hide success label - c#

I've got a ValidationSummary and SuccessLabel in the MasterPage
When the SuccessLabel has detail in it, and then the ValidationSummary then fails validation I want it to hide the SuccessLabel and only show the ValidationSummary.
<div id="ApplicationStatus" class="ValidationSummaryContainer">
<asp:Label ID="StatusLabel" CssClass="SuccessSummary" runat="server"
Visible="false"></asp:Label>
<asp:Label ID="WarningLabel" CssClass="WarningSummary" runat="server"
Visible="false"></asp:Label>
<asp:ValidationSummary ID="ErrorValidationSummary" runat="server"
CssClass="ValidationSummary" DisplayMode="List" />
<asp:CustomValidator ID="ErrorCustomValidator" runat="server"></asp:CustomValidator>
</div>
<div id="ApplicationContent" class="ApplicationContentContainer">
<asp:ContentPlaceHolder ID="MainContent" runat="server">
</asp:ContentPlaceHolder>
</div>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
StatusLabel.Text = "Successfully loaded record";
}
}
<asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
<asp:Textbox ID = "Text1" runat="server"/>
<asp:RequiredFieldValidator id="InputTextBoxRequiredFieldValidator" runat="server"
ControlToValidate="Text1" Visible="false" CssClass="InlineNoWrap" Enabled="true">
</asp:RequiredFieldValidator>
<asp:Button ID = "Button1" runat="server" Text="Submit"/>
</asp:Content>
I'm trying to find a way in JavaScript to catch the validation error and hide the StatusLabel.
I don't want to have to put a javascript function on every button on every page that uses the MasterPage.
Thanks,
Alex

How about something like this:
protected void Submit(object sender, EventArgs e)
{
if (IsValid)
{
StatusLabel.Visible = true;
}
else
{
StatusLabel.Visible = false;
}
}

Your validation code are totally miss lot of fields.
ok now we are going your pint .
Set visible false in your label for page load event
then success time add the label text ,and set visible true
you miss control to validate and validationgroup and display fields
please see this sample

Related

Calling asp net button click event with JS will not call server side event

Sorry to post perhaps a silly problem here, but I'm at my wits end with it. I have a hidden field with a button inside an update panel like so:
<asp:UpdateProgress runat="server" ID="updprCompLines" AssociatedUpdatePanelID="updpanCompLines">
<ProgressTemplate>
<img src="../Images/ajax-loader.gif" alt="Please wait..." /> </ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel runat="server" ID="updpanCompLines" UpdateMode="Conditional">
<%--<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnFillMembers" />
</Triggers>--%>
<ContentTemplate>
<div>
<asp:HiddenField ID="hdnField" runat="server" />
<asp:Button ID="btnFillMembers" runat="server" style="display:none;"
Text="DummyButton" onclick="btnFillMembers_Click" />
</div>
The update panel also contains a gridview and inside my gridview I have a link button:
<ItemTemplate>
<asp:LinkButton ID="lkbtBenefName" runat="server" Text='<%#Eval("COMPETENCE_CODE") %>'
OnClientClick='<%#Eval("COMPETENCE_LINE_ID", "return SelectedCompetence({0})") %>'/>
</ItemTemplate>
The call is to a JS function that is supposed to call the above button:
<ajaxToolkit:ToolkitScriptManager runat="Server" EnablePartialRendering="true" ID="ScriptManager1" EnablePageMethods="true"/>
<script type="text/javascript">
function SelectedCompetence(CompetenceLineId) {
document.getElementById('<%= hdnField.ClientID %>').value = CompetenceLineId;
var clickButton = document.getElementById('<%= btnFillMembers.ClientID %>');
clickButton.click();
}
</script>
Button click event method:
protected void btnFillMembers_Click(object sender, EventArgs e)
{
lblGvMemError.Text = "";
lblGvMemError.ForeColor = Color.Red;
if (hdnField.Value != null || hdnField.Value.ToString() != "")
{
try
{
int CompLineId = Convert.ToInt32(hdnField.Value);
GetSelectedCompLineMembers(CompLineId);
}
catch (Exception ex)
{
lblGvMemError.Text = "Error: " + ex.Message;
}
}
updpanCompLinesMembers.Update();
}
The problem is that while debugging, it never runs the click event and it doesn't give any error messages either. I don't understand, I have a similar form where this works; I don't get why it doesn't here... Any help please?
Have you confirmed that SelectedCompetence is being called via an alert or similar? Additionally, have you made sure that the clickButton variable is being assigned to successfully?
I know this isn't an answer, but don't yet have the reputation to comment, and sometimes it's the easy stuff so maybe this will help! :)

How can I prevent C# from redrawing a <div> I used jQuery to show

Scenario: I have a modal-style div that will be shown when the user clicks a button. At the time the div is shown, I need to get some data from the back-end to fill in some fields. Additionally, I'd like to use the jQuery method I use for all my modal windows (fades in the modal div, displays a background div as well as enabling the use of ESC key or "click offs" to close the modal).
It looks something like this:
<asp:ScriptManager ID="sc" runat="server" />
<asp:UpdatePanel ID="updForm" runat="server">
<ContentTemplate>
<h4>Testing jQuery calls combined with code behind actions</h4>
<div class="pad-content">
<asp:LinkButton ID="lnkShowIt" runat="server" OnClick="lnkShowIt_Click" Text="Load Form" OnClientClick="showForm()" />
<asp:Panel ID="pnlPopup" ClientIDMode="Static" runat="server" CssClass="box-modal" style="width:500px;display:none;z-index:1001">
<div class="header">Edit Estimate X</div>
<div class="content">
<div class="window">
<h5>Test Form</h5>
<asp:TextBox ID="tbxTime" runat="server" />
<br />
<asp:TextBox ID="tbxText" runat="server" Width="150px" />
<br />
<asp:LinkButton ID="lnkValidate" runat="server" CssClass="link-button-blue" Text="Validate" OnClick="lnkValidate_Click" />
</div>
</div>
</asp:Panel>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<div id="backgroundPopup"></div>
So ... lnkShowIt calls both the jQuery (which will show pnlPopup) as well as the C# (which will populate tbxTime).
jQuery method actually just calls another method from a common js library I have that does the modal window stuff - I don't think that actual code is the problem but here is the simple function used for this page:
<script type="text/javascript" language="javascript">
function showForm() {
loadPopup('#pnlPopup');
}
</script>
Code behind methods look like this:
protected void lnkShowIt_Click(object sender, EventArgs e)
{
tbxTime.Text = System.DateTime.Now.Second.ToString();
}
protected void lnkValidate_Click(object sender, EventArgs e)
{
if (tbxTime.Text == tbxText.Text)
{
Response.Redirect("DynamicBoxesWithJQuery.aspx?mode=success");
}
else
{
tbxText.Style["border"] = "1px solid red";
}
}
I'm able to generate some level of success by doing the following but it seems like just a major hack and I have to assume there's a better approach:
protected void lnkShowIt_Click(object sender, EventArgs e)
{
tbxTime.Text = System.DateTime.Now.Second.ToString();
ScriptManager.RegisterStartupScript(this, this.GetType(), "OpenEditor", "<script type='text/javascript'>loadPopup('#pnlPopup');</script>", false);
}
protected void lnkValidate_Click(object sender, EventArgs e)
{
if (tbxTime.Text == tbxText.Text)
{
Response.Redirect("DynamicBoxesWithJQuery.aspx?mode=success");
}
else
{
tbxText.Style["border"] = "1px solid red";
ScriptManager.RegisterStartupScript(this, this.GetType(), "OpenEditor", "<script type='text/javascript'>loadPopup('#pnlPopup');</script>", false);
}
}
It seems like it should be easier than this, but the way the UpdatePanel keeps redrawing (and thus resetting the display:none on pnlPopup) is really causing me fits.
Thanks in advance
Solution I just found: putting the LinkButton in its own UpdatePanel and then the form in its own UpdatePanel and making sure the div that is the actual popup box is not in an UpdatePanel at all.
<h4>Testing jQuery calls combined with code behind actions</h4>
<div class="pad-content">
<asp:UpdatePanel ID="updLink" runat="server">
<ContentTemplate>
<asp:LinkButton ID="lnkShowIt" runat="server" OnClick="lnkShowIt_Click" Text="Load Form" OnClientClick="showForm()" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:Panel ID="pnlPopup" ClientIDMode="Static" runat="server" CssClass="box-modal" style="width:500px;display:none;z-index:1001">
<div class="header">Edit Estimate X</div>
<div class="content">
<asp:UpdatePanel ID="updForm" runat="server">
<ContentTemplate>
<div class="window"style="min-width:500px;">
<h5>Here is a Test Form</h5>
<label>Time:</label>
<asp:TextBox ID="tbxTime" runat="server" />
<br />
<asp:Label ID="lblText" AssociatedControlID="tbxText" runat="server" ViewStateMode="Disabled">Text:</asp:Label>
<asp:TextBox ID="tbxText" runat="server" Width="150px" />
<br />
<asp:LinkButton ID="lnkValidate" runat="server" CssClass="link-button-blue" Text="Validate" OnClick="lnkValidate_Click" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</asp:Panel>
</div>
Seems to do the trick without any Script Registers from the codebehind

C# Dynamically filled DropDownList resets on button OnClick

I am having a bit of a DUH moment and need some help. I have a DropDownList control that gets filled with values on page load and a submit button that does further manipulations. However, when the button is clicked DropDownList returns a value of "-1" and not of the selected option. What is wrong here?
Web page:
<%# Page Language="C#" MasterPageFile="/new/MasterPageA2.master" EnableEventValidation="false" AutoEventWireup="true" CodeFile="Checkout.aspx.cs" Inherits="Common_Checkout" EnableViewState="true" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:UpdatePanel ID="UpdatePanel" runat="server">
<ContentTemplate>
<asp:Label runat="server" ID="test11"></asp:Label>
<asp:DropDownList ID="ddlbillingcountry" required="true" EnableViewState="true" runat="server"></asp:DropDownList>
<asp:Button ID="ImageButton1" AlternateText="Proceed" OnClick="ImageButton1_Click" CausesValidation="false" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
<ProgressTemplate>
<p>Loading...</p>
</ProgressTemplate>
</asp:UpdateProgress>
</asp:Content>
Code behind:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
PopulateCountry(ddlbillingcountry);
}
}
private void PopulateCountry(DropDownList Controlname) {
DatasetTableAdapters.CountryTableAdapter _CountryTableAdapter = new DatasetTableAdapters.CountryTableAdapter();
Controlname.ClearSelection();
Controlname.Items.Clear();
DataTable _DataTable = _CountryTableAdapter._Eco_Country_Select();
Controlname.DataSource = _DataTable;
Controlname.DataTextField = "CountryName";
Controlname.DataValueField = "Country";
Controlname.DataBind();
Controlname.Items.Insert(0, new ListItem("- Select Country -", ""));
}
protected void ImageButton1_Click(object sender, EventArgs e) {
test11.Text += "<p>clicked " + ddlbillingcountry.SelectedIndex + " - " + ddlbillingcountry.SelectedValue.ToString();
}
You could set the datasource property to the name of a function which returns a dataset.
Try datasource='<%# PopulateCountry("ddlbillingcountry") %>' but you will need to change or overload the function to change the argument to a string, remembering to set the datavaluefield and datatextfield.Or you may want to create a separate function and call that with no arguments.

ListView Visible property

I have a search results page where the list views visible property is always false on the first page load even though I set the value to true as seen below. It seems line is being ignored? Is there a reason why this property cannot be set on the first load?
EDIT: Page load Event
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.QueryString["query"] != null)
{
_searchTerm = Request.QueryString["query"].ToString();
GetSearchResults();
txtSearchBox.Text = _searchTerm;
}
}
}
ListView Markup
<asp:PlaceHolder runat="server" ID="SearchResults" Visible="false">
...
<asp:ListView id="lvSearch" runat="server">
<LayoutTemplate>
<ul id="SearchResultsList">
<asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder>
</ul>
</LayoutTemplate>
<ItemTemplate>
<li class="searchResult">
<h2><%#DataBinder.Eval(Container.DataItem, "Title")%></h2>
<p><%#DataBinder.Eval(Container.DataItem, "HighlightedPreview")%></p>
<%#DataBinder.Eval(Container.DataItem, "URL")%>
</li>
</ItemTemplate>
</asp:ListView>
<div runat="server" id="NoResults" visible="false">
<p>The current search has returned no results. Please enter another search term in the box above.</p>
</div>
</asp:PlaceHolder>
Check that it is not in the DIV-NoResults or some other container that is going invisible.

updatepanel and javascript include file

I have found many solution for my issue but none doesn't work in my scenario.
I have created a test project to demo my concept.
Basically, there is a page that host a user control...
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<uc1:WebUserControl1 ID="WebUserControl11" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
WebUserControl1 has a dropdownlist and two other webusercontrols (to be displayed based on the selection of dropdownlist element) inside updatepanel as below.
<%# Register Src="WebUserControl2.ascx" TagName="WebUserControl2" TagPrefix="uc2" %>
<%# Register Src="WebUserControl3.ascx" TagName="WebUserControl3" TagPrefix="uc3" %>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
AutoPostBack="True">
</asp:DropDownList>
<asp:Panel ID="pnlCreditCard" Visible="false" runat="server">
<uc2:WebUserControl2 ID="WebUserControl21" runat="server" />
</asp:Panel>
<asp:Panel ID="pnlGiftCard" Visible="false" runat="server">
<uc3:WebUserControl3 ID="WebUserControl31" runat="server" />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
Code behind file for WebUserControl1 is .....
public enum PaymentMethod
{
CreditCard = 0,
GiftCard
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindPaymentMethods(Enum.GetValues(typeof(PaymentMethod)));
}
private void BindPaymentMethods(Array paymentMethods)
{
DropDownList1.DataSource = paymentMethods;
DropDownList1.DataBind();
if (paymentMethods.Length > 0)
{
DropDownList1.SelectedIndex = 0;
UpdateCreditOrGiftCardPanelVisibility();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
UpdateCreditOrGiftCardPanelVisibility();
}
private void UpdateCreditOrGiftCardPanelVisibility()
{
if(DropDownList1.SelectedValue == Enum.GetName(typeof(PaymentMethod),PaymentMethod.CreditCard))
{
pnlGiftCard.Visible = false;
pnlCreditCard.Visible = true;
}
else if (DropDownList1.SelectedValue == Enum.GetName(typeof(PaymentMethod), PaymentMethod.GiftCard))
{
pnlCreditCard.Visible = false;
pnlGiftCard.Visible = true;
}
}
Now, the problem starts here...There is an external javascript file [JScript1.js] (embedded resource) which basically is used to display an alert box.
<script language="javascript" type="text/javascript">
window.onload = function() {
alert('creditcard form');
}
WebUserControl2.ascx.cs code behind is
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptInclude(this.Page, this.Page.GetType().BaseType, "JScript1", Page.ClientScript.GetWebResourceUrl(this.Page.GetType().BaseType, "WebApplication1.JScript1.js"));
}
Alert window doesn't get displayed when I change the dropdownlist value. Even the script is getting registered three times (look in the firebug)
Need to use ScriptInclude instead of ScriptBlock as the original JS file is too big.
Can email the test app....
Thanks in Advance
After working around a bit, I found the solution.
I registered a ScriptManagerProxy in WebUserControl2.ascx
<asp:ScriptManagerProxy ID="ScriptManager1" runat="server" >
<Scripts>
<asp:ScriptReference Assembly="WebApplication1" Name="WebApplication1.JScript1.js" />
</Scripts>
</asp:ScriptManagerProxy>
Then on the code behind of the same control, added...
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
ScriptManager.RegisterStartupScript(this, GetType(), "test", "doSomething();", true);
}
and the JScript1.js file looks like below.
function doSomething() {
alert('via dosomething control2 form');
}
Hope that helps. Though I had to litter around more in my practical scenario but this was certainly the way I got it working.
Thanks,

Categories