Find failed validators asp.net - c#

I have a page, where I want to log every validation message which the user failed to meet the requirements the associated field.
The problem is my postback/button click never occurs (maybe because of clientside validation), and therefore the logging never takes place before the user actually got every field right (no validation errors).
The button click event method:
protected void btnNext_Click(object sender, EventArgs e)
{
Page.Validate();
if(Page.IsValid)
{
//code
}
else
{
foreach (IValidator validator in Validators)
{
if (!validator.IsValid)
{
PageValidatorErrors error = new PageValidatorErrors
{
WebsiteID = AppState.WebsiteID,
Page = Request.Url.AbsolutePath,
URL = Request.Url.ToString(),
UserIP = Tools.GetIP(),
ErrorMessage = validator.ErrorMessage,
CreatedDate = DateTime.Now
};
pageValidatorErrorsRep.insert(error);
}
}
}
}
Any ideas, how I could log theese messages?
Edit:
<script type="text/javascript">
function validatePage()
{
if (window.Page_IsValid != true)
{
//Page_Validators is an array of validation controls in the page.
if (window.Page_Validators != undefined && window.Page_Validators != null)
{
//Looping through the whole validation collection.
for (var i = 0; i < window.Page_Validators.length; i++)
{
window.ValidatorEnable(window.Page_Validators[i]);
//if condition to check whether the validation was successfull or not.
if (!window.Page_Validators[i].isvalid)
{
var errMsg = window.Page_Validators[i].getAttribute('ErrorMessage');
alert(errMsg);
}
}
}
}
}
</script>

Here is part of the solution, you can get the validates/true false by invoking it client side:
http://razeeb.wordpress.com/2009/01/11/calling-aspnet-validators-from-javascript/
function performCheck()
{
if(Page_ClientValidate())
{
//Do something to log true/ false
}
}

Try to change EnableClientScript property on all validators to false. All your validations will occur only on server side.

Related

ASP.net onPageClose event

I'm trying to find a way of opening a page from a button if its NOT already open.
What I have so far is 2 pages.
Default page opens Option page via a button like:-
protected void btnCreateNewWindow_Click(object sender, EventArgs e)
{
if (SharedMethods.Is_Page_Displayed == 0)
{
ClientScript.RegisterStartupScript(typeof(Page), "Order", "<script type='text/javascript'>window.open('Option1.aspx', '', 'fullscreen = yes')</script>");
SharedMethods.Is_Page_Displayed = 1;
}
}
Shared Session code:-
namespace ns_SharedMethods
{
public class SharedMethods
{
#region Session
public static String sIs_Page_Displayed = "Is_Page_Displayed";
#endregion Session
public static int Is_Page_Displayed
{
get
{
if (System.Web.HttpContext.Current.Session[sIs_Page_Displayed] != null)
{
return (Convert.ToInt32(System.Web.HttpContext.Current.Session[sIs_Page_Displayed]));
}
else
{
return (0);
}
}
set
{
System.Web.HttpContext.Current.Session[sIs_Page_Displayed] = value;
}
}
public static String Is_The_Page_Displayed()
{
if (Is_Page_Displayed == 1)
{
return ("YES");
}
else
{
return ("NO");
}
}
}
}
I've tried is using a Session variable as a flag to denote the page is open/closed.
Is it possible to trigger an OnClosePage event in the second Page to set a Session variable "Is_Page_Displayed = 0"?
Any examples is appreciated.
tia
PS I've tried to publish all pages .aspx source code but the formatting was being distorted :(
Base on the initial code used, add:-
On "Option1.aspx"
Add this to the source:-
<script>
// Window Event to trigger when the page has closed
window.onbeforeunload = function (event)
{
// C# method called from the Java Script
PageMethods.SetWebPageClosedSession();
}
</script>
And this under the "< body > < form id="form1" runat="server" >"
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
Add this to the Option1.aspx.cs:-
[System.Web.Services.WebMethod]
public static void SetWebPageClosedSession()
{
// Method called from the .aspx Script function WebPageClosed()
SharedMethods.Is_Page_Displayed = 0;
}
So what I've done is use the window.onbeforeunload event, in Option1.aspx, to call a C# method to set a Session variable. The Default.aspx page checks prior to trying to open Option1.aspx

Is there a way how to step out form method and return page with updated element?

I have couple of method in code behind on asp.net application. I would like to return messages to user in Label in case of something happen during execution and stop execution.
Code is just as sample what I'm trying to achieve.
I already tried:
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
Response.Redirect("to same page");
Example: (I don't want to execute unzipFile method. I would like to reload current page with updated label)
protected void btnUpload_Click(object sender, EventArgs e) {
uploadFile(Server.MapPath("~/") + filename);
unzipFile(string newFile);
}
protected void uploadFile(string newFile) {
if (newFile != null)
{
Label.Text="This is not valid file!"
//stop processing load file with updated label
}
if (newFile.ContentType != "application/x-zip-compressed") {
Label.Text="This is not valid file!"
//stop processing load file with updated label
}
}
Just don't redirect. The postback is already to the current page and should render the current page unless anything tells is not to. Consider a simple case:
protected void Page_Load(/.../)
{
// set some values on the page
}
protected void btnClick(/.../)
{
label1.Text = "This is a test";
}
With only that code in the button click handler, the current page will reload after clicking the button and the only visible change will be that text output.
Your case isn't really different. Set the labels and don't redirect. For example:
if (newFile != null)
{
Label.Text = "This is not valid file!";
}
else if (newFile.ContentType != "application/x-zip-compressed")
{
Label.Text = "This is not valid file!";
}
else
{
// process the file
Response.Redirect("SomewhereElse.aspx");
}
However you structure the logic, ultimately your goal is to not do any more processing once you have your error condition and just allow the event handler to complete and the page to re-render.
Note: I think you also meant == null, and you can simplify the conditions. Consider:
if (newFile == null || newFile.ContentType != "application/x-zip-compressed")
{
Label.Text = "This is not valid file!";
}
else
{
// process the file
Response.Redirect("SomewhereElse.aspx");
}
If you don't want the else, you can accomplish the same with a return:
if (newFile == null || newFile.ContentType != "application/x-zip-compressed")
{
Label.Text = "This is not valid file!";
return;
}
// process the file
Response.Redirect("SomewhereElse.aspx");

Invoke Javascript method from code-behind based on a condition.

This is my javascript method in .aspx file. I want to invoke this method from code-behind based on a certain condition:
function confirmboxAndHideMessage() {
//HideMessage();
var response = confirm("are you sure?.");
if (response == true) {
document.getElementById("<%=chkValidated.ClientID%>").checked = true;
HideMessage();
}
else {
HideMessage();
return true;
}
}
The condition upon which I want to invoke is something like this:
if (obj.fkValidationStatusId.HasValue && obj.fkValidationStatusId.Value.Equals(1))
{
btnProceedAddNewRecords.Attributes.Add("OnClick", "javascript:return confirmboxAndHideMessage();");
}
else
{
btnProceedAddNewRecords.Attributes.Remove("OnClick");
}
This condition is being exercised in a method which is called in PageLoad event inside
if (!IsPostBack) { /* condition */ }
It is not working and my guess is that the way i am adding the method in button attribute is wrong. My request is that, kindly suggest a way I can invoke this javascript method from my code-behind based on the stated condition. If you think that my approach is flawed, Please do suggest Alternatives. Thanks.
use to set/unset OnClientClick
if (obj.fkValidationStatusId.HasValue && obj.fkValidationStatusId.Value.Equals(1))
{
btnProceedAddNewRecords.OnClientClick="return confirmboxAndHideMessage();";
}
else
{
btnProceedAddNewRecords.OnClientClick="retun false;";
}
Just add the following code where the condition is like
public void test()
{
String name = "test";
if (name == "test")
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "hdrEmpty", "if(confirm('are you sure you want to continue?')==true){ Testfunction(); };", true); return;
}
}
I am sure it will work for you.
You should return true or false from the function. You probably want to return true for a positive response:
function confirmboxAndHideMessage() {
var response = confirm("are you sure?.");
if (response == true) {
document.getElementById("<%=chkValidated.ClientID%>").checked = true;
HideMessage();
return true;
} else {
HideMessage();
return false;
}
}
Use lowercase for the event name (as XHTML is picky about that), and remove javascript: from the code:
btnProceedAddNewRecords.Attributes.Add("onclick", "return confirmboxAndHideMessage();");
Put the code that sets the attribute outside the check for IsPostBack, otherwise it will not be updated when the condition changes.

Can you clear Page.Request.QueryString?

My problem is as follows:
I am adding a variable to the URL that should trigger a search when the page loads, depending on what is in the variable. If you navigate to that same page without the variable then it shouldn't do anything special on page load. I figured that the following would do the trick:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.Request.QueryString["cell"] != null)
{
txtCell.Text = Page.Request.QueryString["cell"];
Lookup_Cell(Page.Request.QueryString["cell"]);
//BUGGED, this keeps running when i try a new search
//Page.Request.QueryString["cell"] = null;
}else{
//do nothing, empty string
}
}
This worked like a charm, but i have a search button of the form that is supposed to call the Lookup_Cell method for a cell you specify in a TextBox. i need to make Page.Request.QueryString empty so next time the page loads it won't fire this special OnLoad. I tried:
Page.Request.QueryString["cell"] = null;
but that didn't work. I looked for other methods, but can't find a definite answer.
You can make a simple PostBack check and when there is a post back, get the string from your text box.
string cFinalQueryString = "";
if(!IsPostBack)
{
if (Page.Request.QueryString["cell"] != null)
{
cFinalQueryString = Page.Request.QueryString["cell"];
}else{
//do nothing, empty string
}
}
else
{
cFinalQueryString = txtCell.Text;
}
txtCell.Text = cFinalQueryString;
Lookup_Cell(cFinalQueryString);
Or alternative, when you have post back, redirect to new page with new 'cell' query
if(IsPostBack && Page.Request.QueryString["cell"] != txtCell.Text)
{
Responce.Redirect("CurrentPage.aspx?cell=" + UrlEncode(txtCell.Text), true);
return ;
}
The querystring is sent by the browser with each request to that URL.
It sounds like you want to redirect to a URL without a querystring.

strange session problem

I have this field in my session class:
public bool IsCartRecentlyUpdated
{
get
{
if (this.session["IsCartRecentlyUpdated"] != null)
{
return (bool)this.session["IsCartRecentlyUpdated"];
}
else
{
this.session["IsCartRecentlyUpdated"] = false;
return (bool)this.session["IsCartRecentlyUpdated"];
}
}
set
{
this.session["IsCartRecentlyUpdated"] = value;
}
}
Whenever a user adds a product to the cart I put this value on true:
public void AddToCart(Product product, int quantity)
{
IsCartRecentlyUpdated = true;
//other code for updating the cart
}
Adding a product to the cart does a postback so I can show a message (ëg: Product added succesfully) in Page_Load of the General Master page where the shopping cart is located, when a product has just been added to the cart:
protected void Page_Load(object sender, EventArgs e)
{
if (this.sessionsUtil.IsCartRecentlyUpdated)
{
this.lblCartWarning.Text = (string)GetLocalResourceObject("CartWarning");
imgCardLogos.Visible = false;
}
else
{
this.lblCartWarning.Text = String.Empty;
imgCardLogos.Visible = true;
}
//other code
//put it back to false to not show the message each time the page is loaded
this.sessionsUtil.IsCartRecentlyUpdated = false;
}
Well this code works great locally but on the server it does not show the message after adding the product to the cart but on the second page loading...
(I guess that on the server somehow the page is loading before the session var is updated - extremely strange)
Do you know why? I do not see any problem in the code...
Strange issues like this might be easier to solve using IIS express
http://weblogs.asp.net/scottgu/archive/2011/01/03/vs-2010-sp1-beta-and-iis-developer-express.aspx

Categories

Resources