Validation Before Postback Event on Masterpage Asp.net - asp.net

I was wondering if anyone knew of a way to do some client side validation with jquery and then run the postback event manually for a asp.net control?
Here's a sample Master page
i.e.
<script type="text/javascript">
$(document).ready(function() {
$("#<%=lnkbtnSave.ClientID %>").click(function() {
alert("hello");
// Do some validation
// If validation Passes then post back to lnkbtnSave_Click Server side Event
});
});
</script>
<asp:LinkButton ID="lnkbtnSave" runat="server" onclick="lnkbtnSave_Click" ><asp:Image ID="Image3" runat="server" ImageUrl="~/images/save.gif" AlternateText="Save" />Save</asp:LinkButton>
Master Page Code Behind
public delegate void MasterPageMenuClickHandler(object sender, System.EventArgs e);
public event MasterPageMenuClickHandler MenuButton;
protected void lnkbtnSave_Click(object sender, EventArgs e)
{
// Assign value to public property
_currentButton = "Save";
// Fire event to existing delegates
OnMenuButton(e);
}
protected virtual void OnMenuButton(EventArgs e)
{
if (MenuButton != null)
{
//Invokes the delegates.
MenuButton(this, e);
}
}
Content Page Code behind
protected void Page_Load(object sender, EventArgs e)
{
Master.MenuButton += new Form.MasterPageMenuClickHandler(Master_MenuButton);
}
void Master_MenuButton(object sender, EventArgs e)
{
switch (Master.CurrentButton)
{
case "Save":
Save();
break;
case "New":
Response.Redirect("ContentPage.aspx");
break;
default:
break;
}
}
Also the control lnkbtnSave is in a master page so how would i determine which content page i'm on since each content page will have it's own controls to validate.
Thanks for any help

If you look at it in reverse it could be simplified. Instead of doing validation and then initiating the postback, you could validate and prevent the postback if needed.
$('#<%= lnkbtnSave.ClientID %>').click(function(e) {
if (!validate()) {
e.preventDefault(); //will stop the page from posting back.
}
});
If you really need to initiate the postback (and do it the other way) you could explicitly call the __doPostBack() function that ASP.NET puts on the page for you after doing your validation.
// This does the exact same thing as above, but it explicitly calls __doPostBack
// If you use the above code __doPostBack will be called automatically for you.
$('#<%= lnkbtnSave.ClientID %>').click(function(e) {
if (validate()) {
__doPostBack('<%= lnkbtnSave.ClientID %>','');
}
e.preventDefault();
});
Let me know if any of this needs clarification.

For the first question you should be able to just return true to cause the linkbutton to postback and return false to stop it.
$(document).ready(function() {
$("#<%=lnkbtnSave.ClientID %>").click(function() {
alert("hello");
var isValid = false;
// Do some validation
return isValid;
});
});
For your second question, you could have each page add their own version of the validation script, and have the function in the masterpage use it to determine validity:
Master Page:
$(document).ready(function() {
$("#<%=lnkbtnSave.ClientID %>").click(function() {
return pageIsValid();
});
});
Content Page:
function pageIsValid() {
var isValid = false;
//validation logic
return isValid;
}

You can just use a CustomValidator control and set it's ClientValidationFunction property.

Related

How to pass arguments in alert message - aspx page alert

I would like to pass arguments in an alert message.
var bankCodeName = "ABC";
alert("<%= Common.GetResourceText("BankCodeSearch_SearchByBranchAlert") %>", bankCodeName);
Default.aspx.cs
public partial class _Default: Page
{
private string clients;
public string Clients { get { return clients; } }
protected void Page_Load(object sender, EventArgs e)
{
clients = "test msg";
}
}
Default.aspx
you need to put your javascript code inside Script
<script type="text/javascript">
//your code
</script>
tag so the Aspx renderer can understand the difference between HTML and Javascript code.
<script type="text/javascript">
var bankCodeName = "ABC";
var client='<%= Clients %>';
alert(bankCodeName+client);
</script>
var client='<%= Clients %>'; line saves your code behind variable value to JavaScript variable.

Value returned from jQuery is always null when accessing it from codebehind in asp.net

My master page contains a menu which is dynamically created in <ul><li><li><ul/> format.
When I click on it, I want to pass its ID to codebehind for passing it into base class for its permission. But am getting value from jQuery always null in codebehind - but am getting value in jQuery function.
<script type="text/javascript">
$(document).ready(function () {
$('#nav li').click(function () {
debugger;
var vals = $(this).text();
document.getElementById('hdnForLabel').value = vals ;
});
});
</script>
This page load am using in Master Page.
protected void Page_Load(object sender, EventArgs e)
{
GetMenus();
string pageids = hdnForLabel.Value;
BasePage BasePage = new BasePage();
BasePage.LoadSettings(pageids );
}
Have you checked if the ID of your rendered hidden control is really 'hdnForLabel'? It might be something along the line of 'ctl00_hdnForLabel'.
You could use jQuery to check if the value has been set on the client side:
<script type="text/javascript">
$(document).ready(function () {
$('#nav li').click(function () {
debugger;
var vals = $(this).text();
document.getElementById('hdnForLabel').value = vals ;
alert( "Value: " + $("#hdnForLabel").val());
});
});
</script>
Please note that a value set for hdnForLabel.Value is only available when the page is sent back to the server via postback
protected void Page_Load(object sender, EventArgs e)
{
GetMenus();
if (IsPostBack) {
string pageids = hdnForLabel.Value;
BasePage BasePage = new BasePage();
BasePage.LoadSettings(pageids );
}
}

Prevent double submiting in asp:CommandField

Have this code:
<asp:UpdatePanel ID="id">
<asp:CommandField ButtonType="Image" InsertImageUrl="url/here" ShowInsertImage="true" ValidationGroup="valGr" />
</asp:UpdatePanel>
How to prevent double clicking on this button in C# code.
You can first create a flag that hold the submit and add it to the form. Then open and close that flag when the UpdatePanel go for update and while is waiting for the return.
For example this code is allow the submit of the form (and of the UpdatePanel) only when the
fAlloToSubmit is true:
<script>
var fAlloToSubmit = true;
function AllowFormToRun()
{
if(!fAlloToSubmit)
alert("Please wait for the page to fully re-loaded.");
return fAlloToSubmit;
}
</script>
and on code behind you set that on the form.
protected void Page_Load(object sender, EventArgs e)
{
Page.Form.Attributes["onsubmit"] = "return AllowFormToRun();";
}
And now for the UpdatePanel, you open that flag the moment you go for update, eg the moment you click that command as:
<script>
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
function InitializeRequest(sender, args) {
// here is run when you click the command on the UpdatePanel
fAlloToSubmit = false;
}
function EndRequest(sender, args) {
// here is come after the upadate of the command
fAlloToSubmit = true;
}
</script>
The trick here is that I hold the form to submit and not looking every control on page to disable it.

Validation, Page events and ViewState

i have two buttons on the page. One button is responsible for text fields validation that are to do with registration and the other with loging in. The problem was when i press one of the buttons it refreshes the page and shows all the invalid fields (i dont want the registration fields to be checked by the RequiredFieldValidator whent the user presses the login button).
so what i did i used the initialization event.. to prevent this from happening...
static bool oneButtonPressed;
protected void Page_Init(object sender, EventArgs e)
{
if (oneButtonPressed)
{
REgisterAge.Visible = false;
RegisterAge2.Enabled = false;
RegisterAge3.Enabled = false;
RegisterPassword.Enabled = false;
RegisterPassword2.Enabled = false;
RegisterEmail.Enabled = false;
RegisterEmail2.Enabled = false;
}
else
{
EntryPasswordRequiredFieldValidator10.Enabled = false;
EntryNameEntryRequiredFieldValidator9.Enabled = false;
}
}
protected void entry_Click(object sender, EventArgs e)
{
oneButtonPressed = true;
}
protected void submitButton_Click(object sender, EventArgs e)
{
oneButtonPressed = false;
}
}
The probelm here is that the bool is always false when the page is posted back and loads again.. i do remember my teacher saying i could either use a ViewState or a static variable/method to preserve my values. Am i being wrong here.. do i have to use the ViewState?
Why don't you assign a validationgroup to each of the fields + the relevant submit button.
Different validation groups will ensure that validation won't fire on the irrelevant form.
<asp:TextBox runat="server" ID="txtName" ValidationGroup="vRegistration"></asp:TextBox>
<asp:LinkButton runat="server" ID="btnSubmit" ValidationGroup="vRegistration"></asp:LinkButton>

Custom TextBox with built-in Validator: server side validation not firing

I have a class that looks like this:
public class TextField : TextBox
{
public bool Required { get; set; }
RequiredFieldValidator _validator;
protected override void CreateChildControls()
{
base.CreateChildControls();
_validator = new RequiredFieldValidator();
_validator.ControlToValidate = this.ID;
if(Required)
Controls.Add(_validator);
}
public override void Render(HtmlTextWriter tw)
{
base.Render(tw);
if(Required)
_validator.RenderControl(tw);
}
}
This has been working for a while in a internal application where javascript is always enabled. I recently noticed that an upstream javascript error can prevent the validators from firing, so the server side validation should kick in... right? right?
So the Page.IsValid property always returns true (I even tried explicitly calling Page.Validate() before-hand).
After some digging, I found that the validator init method should add the validator to the page, but due to the way I'm building it up, I don't think this ever happens. Thus, client side validation works, but server side validation does not.
I've tried this:
protected override OnInit()
{
base.OnInit();
Page.Validators.Add(_validator); // <-- validator is null here
}
But of course the validator is null here (and sometimes it's not required so it shouldn't be added)... but OnInit() is really early for me to make those decisions (the Required property won't have been loaded from ViewState for example).
Ideas?
The CreateChildControls is basically for the controls that have childs. RequiredFieldValidator is like a sibling to TextBox.
Here is the code that works for me:
public class RequiredTextBox : TextBox
{
private RequiredFieldValidator _req;
private string _errorMessage;
public string ErrorMessage
{
get { return _errorMessage; }
set { _errorMessage = value; }
}
protected override void OnInit(EventArgs e)
{
_req = new RequiredFieldValidator();
_req.ControlToValidate = this.ID;
_req.ErrorMessage = _errorMessage;
Controls.Add(_req);
base.OnInit(e);
}
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
base.Render(writer);
_req.RenderControl(writer);
}
}
And here it the ASP.NET page behind:
protected void SubmitClick(object sender, EventArgs e)
{
if(Page.IsValid)
{
// do something
}
}
And here is the ASPX code:
<MyControl:RequiredTextBox runat="server" ErrorMessage="Name is required!" ID="txtName"></MyControl:RequiredTextBox>
<asp:Button ID="Btn_Submit" runat="server" Text="Submit" OnClick="SubmitClick" />
Validators have to inherit from BaseValidator.

Resources