CustomValidator OnServerValidate Not Working - c#

I am trying to utilize a CustomValidator using the keyword "OnServerValidate"
Here is where I have it setup in my .aspx file:
<div class="label">
<div><label for="parentemail1">Email Address</label></div>
<div><asp:TextBox ID="parentemail1" runat="server" MaxLength="40" Columns="40"></asp:TextBox></div>
<asp:CustomValidator id="ParentEmail1Required"
ControlToValidate="parentemail1"
Display="Dynamic"
ErrorMessage="Required"
ValidateEmptyText="true"
OnServerValidate="ServerValidator"
runat="server"/>
</div>
and here is the C# code behind method for OnServerValidate:
protected void ServerValidator(object source, ServerValidateEventArgs args)
{
args.IsValid = false;
}
Am I missing something, shouldn't the CustomValidator fire when the form is submitted?
I've read through a bunch of posts and even tried this with a RequiredFieldValidator on the same control but no luck. I have this working with ClientValidationFunction but I want to access the properties in the code behind instead of the DOM.
Any help would be greatly appreciated.

Try this
protected void ServerValidator(object source, ServerValidateEventArgs args)
{
if(args.IsValid == false)
return;
Response.Redirect("NextPage.aspx");// It will not fire if page is not valid.
}

Well, the argument args is not sent to server and that's why you don't get server message. Add a button can do this.
Change the code to
<div>
<div class="label">
<div><label for="parentemail1">Email Address</label></div>
<div><asp:TextBox ID="parentemail1" runat="server" MaxLength="40" Columns="40"></asp:TextBox>
<br />
<asp:Button ID="btnSendData" runat="server" Text="Send Data" />
</div>
<asp:CustomValidator id="ParentEmail1Required"
ControlToValidate="parentemail1"
Display="Dynamic"
ErrorMessage="Required"
ValidateEmptyText="true"
OnServerValidate="ServerValidator"
runat="server" SetFocusOnError="True"/>
</div>
</div>

Related

Creating Comment box With Reply Option using Asp.Net

I am tring to Create a Comment box having reply option for my Website
Below Is My aspx page
<div>
<asp:Repeater runat="server" ID="repAnswer">
<ItemTemplate>
<h6>Answer</h6>
<p><%# Eval("Answer") %></p>
<asp:Label runat="server" ID="lblAnsId" Text='<%# Eval("AnsId")%>' Visible="false"></asp:Label>
<a class="link" id='lnkReplyParent<%#Eval("AnsId") %>' href="javascript:void(0)" onclick="showReply(<%#Eval("AnsId") %>);return false;">Reply</a>
<a class="link" id="lnkCancle" href="javascript:void(0)" onclick="closeReply(<%#Eval("AnsId") %>);return false;">Cancle</a>
<div id='divReply<%#Eval("AnsId") %>' style="display:none;">
<asp:TextBox ID="textCommentReplyParent" CssClass="input-group" runat="server" Width="300px" TextMode="MultiLine" ></asp:TextBox>
<br />
<asp:Button ID="btnReplyParent" runat="server" Text="Reply" OnClick="btnReply_Click" /></div>
</ItemTemplate>
</asp:Repeater>
</div>
<div style="margin-top:100px">
<h5>Your Answer</h5>
<hr />
<CKEditor:CKEditorControl ID="txtAddAnswer" BasePath="Admin/ckeditor/" runat="server">
</CKEditor:CKEditorControl>
<asp:Button runat="server" ID="btnAnswer" Text="Submit Answer" OnClick="btnAnswer_Click"/>
</div>
i have used Repeater to bind my answer or comment. Inside the repeater i have given two link pne is of reply other is of cancel.when someone click on the reply a new textbox and button open which is used to give the reply
Below is my cs page
protected void btnReply_Click(object sender, EventArgs e)
{
foreach (RepeaterItem row in repAnswer.Items)
{
Label lblNewAnsIdholder = (Label)row.FindControl("lblNewAnsIdholder");
TextBox txtReplyToAnswer = (TextBox)row.FindControl("txtReplyToAnswer");
OnlineSubjects onlinesub = new OnlineSubjects()
{
reply = txtReplyToAnswer.Text.Trim(),
AnsId = Convert.ToInt32(lblNewAnsIdholder.Text.ToString())
};
onlinesub.addAnswer();
}
}
i dont know how to use textbox in repeater but after searching it through google i get something like this which i am not sure thats right or wrong.
And the line where i have created my object for my class i am getting error from there
I am tring to pass the value of textbox as a paramter
Plz help me to do this.
Thank You
You Should try,
TextBox txtReplyToAnswer = ((TextBox)row.FindControl("txtReplyToAnswer")).Text;
Hope this will work.

Textchange event not working

I am doing a preview of what I am currently typing in a web page using ASP.NET. What I am trying to achieve is that whenever I type or change text in the textbox, the <h3> or label element will also change and always copy what the textbox value is without refreshing the browser. Unfortunately I cannot make it work. Here is what I tried.
.ASPX
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
<div class="Padding10px">
<h1 class="Margin0px">Preview</h1>
<hr />
<p></p>
<h3 id="NewsTitlePreview" class="TextAlignCenter" runat="server">Title</h3>
<h5 id="NewsContentPreview" class="TextIndent50px TextAlignJustify" runat="server">Content</h5>
</div>
</div>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
Title
<asp:TextBox ID="Titletxt" runat="server" OnTextChanged="Titletxt_TextChanged"></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" runat="server" onchange="Contenttxt_TextChanged"></asp:TextBox>
<asp:Button ID="Submit" runat="server" Text="Submit" />
</div>
.CS
protected void Titletxt_TextChanged(object sender, EventArgs e)
{
NewsTitlePreview.InnerText = Titletxt.Text;
}
protected void Contenttxt_TextChanged(object sender, EventArgs e)
{
NewsContentPreview.InnerText = Contenttxt.Text;
}
I Tried Adding Autopostback = true... but it only works and refreshes the page and i need to press tab or enter or leave the textbox :(
UPDATE: I Tried This - enter link description here But Still Doesnt Work :(
Just add this script function in your code and in body write onload and call that function.
Javascript:
<script type="text/javascript">
function startProgram() {
setTimeout('errorcheck()', 2000);
}
function errorcheck() {
setTimeout('errorcheck()', 2000);
document.getElementById("NewsTitlePreview").innerText = document.getElementById("Titletxt").value
document.getElementById("NewsContentPreview").innerText = document.getElementById("Contenttxt").value
}
</script>
<body onload="startProgram();">
<form id="form1" runat="server">
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
<div class="Padding10px">
<h1 class="Margin0px">Preview</h1>
<hr />
<p></p>
<h3 id="NewsTitlePreview" class="TextAlignCenter" runat="server">Title</h3>
<h5 id="NewsContentPreview" class="TextIndent50px TextAlignJustify" runat="server">Content</h5>
</div>
</div>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
Title
<asp:TextBox ID="Titletxt" runat="server" ></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" runat="server"></asp:TextBox>
<asp:Button ID="Submit" runat="server" Text="Submit" />
</div>
</form>
</body>
You are right in your analysis of the behavior of the control (it only fires the event when you leave the control), even when you have AutoPostBack="True".
MSDN says it all:
The TextBox Web server control does not raise an event each time the user enters a keystroke, only when the user leaves the control. You can have the TextBox control raise client-side events that you handle in client script, which can be useful for responding to individual keystrokes.
So you either have to be satisfied with the current behavior, or set up some client side event handling to do some validation, etc. client side.
Download and include JQuery library. And also modify title and content textbox so they don't change their Id's
Title
<asp:TextBox ID="Titletxt" ClientIDMode="Static" runat="server"></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" ClientIDMode="Static" runat="server"></asp:TextBox>
Then add this script and it will work.
<script>
$(document).ready(function () {
$('#Titletxt').on('input', function () {
$("#NewsTitlePreview").text($(this).val());
});
$("#Contenttxt").on('input',function () {
$("#NewsContentPreview").text($(this).val());
});
});
</script>
One of the best idea...
Just change your code to this. it works
ASPX
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ViewStateMode="Enabled">
<ContentTemplate>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
<div class="Padding10px">
<h1 class="Margin0px">Preview</h1>
<hr />
<p></p>
<h3 id="NewsTitlePreview" class="TextAlignCenter" runat="server">Title</h3>
<h5 id="NewsContentPreview" class="TextIndent50px TextAlignJustify" runat="server">Content</h5>
</div>
</div>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
Title
<asp:TextBox ID="Titletxt" runat="server" OnTextChanged="Titletxt_TextChanged"></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" runat="server" onchange="Contenttxt_TextChanged"></asp:TextBox>
<asp:Button ID="Submit" runat="server" Text="Submit" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
.CS
protected void Titletxt_TextChanged(object sender, EventArgs e)
{
NewsTitlePreview.InnerText = Titletxt.Text;
UpdatePanel1.Update();
}
protected void Contenttxt_TextChanged(object sender, EventArgs e)
{
NewsContentPreview.InnerText = Contenttxt.Text;
UpdatePanel1.Update();
}
Try this it will work this how change event call using jquery dont forget to add google apis
<script>
$('#txtbox').change(function() {
alert("change Event");
});
</script>

Required Field Validator issue validating TextBox value

I have a TextBox which i use to store a url to applied a <asp:HyperLink> control. What i want to do is fire off the RequiredFieldValidator when the TextBox.Text value is empty and the user clicks save. As far as i can tell, my logic is OK, but the validator isn't firing off?
Here's the markup:
<div class="frmRow">
<div class="frmControls">
<asp:Label ID="lblLink" AssociatedControlID="txtImgUrl" runat="server" Text="Image URL"></asp:Label>
<asp:RequiredFieldValidator ID="imgUrlValidator" runat="server" ControlToValidate="txtImgUrl" ErrorMessage="Enter a Valid URL" />
<asp:TextBox ID="txtImgUrl" runat="server" />
</div>
<div class="clearBoth"></div>
</div>
Here is the code to check a valid absolute URL which is inside my btnSave event:
Uri url;
if (!string.IsNullOrEmpty(txtImgUrl.Text))
{
txtImgUrl.Text = Uri.TryCreate(txtImgUrl.Text, UriKind.Absolute, out url) ? url.AbsoluteUri : string.Empty;
}
Save button markup:
<br class="clearBoth" />
<asp:Button ID="btnSave" Text="Save Case study" ImageUrl="~/Assets/Design/buttons/btn-update.gif" CssClass="btn fltr" runat="server" OnClick="btnSave_OnClick" />
<div class="clearBoth"></div>
Shouldn't the RequiredFieldValidator be fired off when TryCreate fails on a dodgy URL and txtImgUrl.Text = ""?
Is there something blatantly obvious that I'm missing here?
Any help is much appreciated
You should check on button click
if (Page.IsValid)
{
lblOutput.Text = "Required field is filled!";
}
else
{
lblOutput.Text = "Required field is empty!";
}
In ASPX in the button add
CausesValidation="true"

How to handle CreateUserWizard Steps in Asp.Net?

I have used asp.net creatuserwizard in my project. And my custom template looks like this
<WizardSteps>
<asp:CreateUserWizardStep ID="CreateUserWizardStep0" runat="server">
<ContentTemplate>
//my custom code is here
</ContentTemplate>
<CustomNavigationTemplate>
</CustomNavigationTemplate>
</asp:CreateUserWizardStep>
Now, in Step2 i have code like this;
<asp:WizardStep ID="CreateUserWizardStep1" runat="server" AllowReturn="False" StepType="Step">
<div class="accountInfo">
<fieldset class="register">
<p>
<asp:Label ID="CityLabel" runat="server" AssociatedControlID="City">City:</asp:Label>
<asp:TextBox ID="City" runat="server" CssClass="textEntry"></asp:TextBox>
</p>
<p>
<asp:Label ID="CountryLabel" runat="server" AssociatedControlID="Country">Country:</asp:Label>
<asp:TextBox ID="Country" runat="server" CssClass="textEntry"></asp:TextBox>
</p>
</fieldset>
</div>
</asp:WizardStep>
So, my question is, how do i insert 'City' textbox value in my user profile as i click on next in step2.
You can handle the NextButtonClick of the Create User Wizard and check for the currentstepindex:
protected void YourCreateUserWizard_NextButtonClick(object sender, WizardNavigationEventArgs e)
{
if (e.CurrentStepIndex == YourStepIndex)
{
...
}
}
You will need to add code to handle the CreatedUser event of the wizard control.
This part should be in the code behind, there you have access to the current state of the wizard:
protected void CreateUserWizard_CreatedUser(object sender, EventArgs e)
{
// Finde the value
var cityField = (TextBox)CreateUserWizard.CreateUserWizardStep1.FindControl("City");
// use the field value todo whatever you want
}

UpdatePanel, ModalPopupExtender, and enter keypress issues

Have an UpdatePanel that contains 2 panels with default buttons set to listen to enter key presses. That UpdatePanel is the PopupControl for a ModalPopupExtender.
Running into an issue when pressing enter in the modal popup in which the entire page posts back. Any ideas? Here are some code snippets (I've removed the extraneous fields...):
<div runat="server" id="divShippingEstimatorPopup" class="shippingEstimatorModalPopup">
<asp:UpdatePanel ID="upPopup" runat="server">
<ContentTemplate>
<asp:Panel runat="server" ID="pnlShippingEstimator" DefaultButton="lnkbtnGetEstimates">
<div class="title content_title">Shipping Estimator</div>
<asp:Label runat="server" ID="lblMessage" />
<table cellpadding="0" cellpadding="0" class="shipping">
<!-- Removed to shorten code snippet -->
<tr>
<td colspan="2">
<div class="buttonHolder">
<Monarch:LinkButtonDefault runat="server" ID="lnkbtnGetEstimates" CssClass="button_action button_margin_right" CausesValidation="false">Get Estimates</Monarch:LinkButtonDefault>
<asp:LinkButton runat="server" ID="lnkbtnCancel" CssClass="button_secondary button_secondary_fixed" CausesValidation="false">Cancel</asp:LinkButton>
<div class="clear"></div>
</div>
<div class="clear"></div>
</td>
</tr>
</table>
</asp:Panel>
<asp:Panel runat="server" ID="pnlShippingOptions" DefaultButton="lnkbtnSetEstimate">
<div class="shippingOptionsHolder" runat="server" id="divShippingOptionsHolder">
<!-- Removed to shorten code snippet -->
<div class="buttonHolder">
<Monarch:LinkButtonDefault runat="server" ID="lnkbtnSetEstimate" CssClass="button_action">Set Estimate</Monarch:LinkButtonDefault>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
Keep in mind the LinkButtonDefault is just this:
public class LinkButtonDefault : LinkButton
{
private const string AddClickScript = "SparkPlugs.FixLinkButton('{0}');";
protected override void OnLoad(EventArgs e)
{
string script = String.Format(AddClickScript, ClientID);
Page.ClientScript.RegisterStartupScript(GetType(), "click_" + ClientID,
script, true);
base.OnLoad(e);
}
}
Finally, here is the rest of the control:
<asp:UpdatePanel runat="server" ID="upGetEstimate">
<ContentTemplate>
<asp:LinkButton runat="server" ID="lnkbtnGetEstimate" CausesValidation="false">Get Estimate</asp:LinkButton>
</ContentTemplate>
</asp:UpdatePanel>
<ajaxToolKit:ModalPopupExtender ID="shippingEstimatorPopupExtender" runat="server" TargetControlID="lnkbtnFake" PopupControlID="divShippingEstimatorPopup" BackgroundCssClass="monarchModalBackground"></ajaxToolKit:ModalPopupExtender>
<asp:LinkButton runat="server" ID="lnkbtnFake" style="display:none;"/>
<Monarch:PopupProgress ID="popupProgressGetEstimate" runat="server" AssociatedUpdatePanelId="upGetEstimate" />
<Monarch:PopupProgress ID="popupProgressGetEstimates" runat="server" AssociatedUpdatePanelId="upPopup" />
Basically, the user clicks Get Estimate, a progress bar appears while it loads the form, the form shows in a modal popup. I'm guessing this is something simple, but I can't just get the right combination to get this working properly.
First of all try what happens if you use your scriptmanager to register script in the code behind.
I use this method for registering scripts:
public static void RegisterStartupScript(Control c, string script)
{
if ((ToolkitScriptManager.GetCurrent(c.Page) as ToolkitScriptManager).IsInAsyncPostBack)
ToolkitScriptManager.RegisterStartupScript(c, c.GetType(), "Script_" + c.ClientID.ToString(), script, true);
else
c.Page.ClientScript.RegisterStartupScript(c.GetType(), c.ClientID, script, true);
}
This checks if you have ScriptManager in your page. If it doesn't, it uses the full postback version.

Categories

Resources