HiddenField empty and Viewstate value null on Page_Load - asp.net

This issue started when trying to get a DevExpress ASPxPopupControl to show after pressing a button. Using popup.ShowOnPageLoad = true; didn't seem to suffice, checking the value on Page_Load shows it reverts to false, even though the code on the server definitely executed.
So I decided to have a variable that reads from and writes to the ViewState so it persists. I then had the variable:
bool ShowPopup
{
get
{
if (ViewState["ShowPopup"] == null)
return false;
return (bool)ViewState["ShowPopup"];
}
set
{
ViewState["ShowPopup"] = value;
}
}
Which was called on the button press by simply ShowPopup = true. When using popup.ShowOnPageLoad = ShowPopup; in Page_Load, ViewState["ShowPopup"] is null and therefore it returns false.
I then tried to use a HiddenField. So I changed ShowPopup to:
bool ShowPopup
{
get
{
return hfShowPopup.Value != "" && hfShowPopup.Value.ToLower() != "false";
}
set
{
hfShowPopup.Value = value.ToString();
}
}
Again using ShowPopup = true on button click, when ShowPopup is read in Page_Load its value is "" and again therefore ShowPopup is false.
I then tried to set the HiddenField directly via hfShowPopup.Value = "true"; and using
popupDuplicatePlayer.ShowOnPageLoad = hfShowPopup.Value != "" && hfShowPopup.Value.ToLower() != "false";
in Page_Load, but again hfShowPopup.Value is empty.
I have used a number of other variables reading from/writing to the ViewState in the same page and they work fine. I know that ViewState and HiddenField might not exist early in the page life cycle but there are being used in Page_Load and so should be fine? I also tried to access them in Page_LoadComplete with the same issues. There are no UpdatePanels on the page so this isn't an issue, is there any other reason for this?
I would assume that the issue with the ViewState, HiddenField AND the ShowOnPageLoad being set directly are related?

Rather silly mistake from me. In the button press I redirected to the current page, rather than allowing the post back. Therefore the values are lost on Page_Load. Very silly, but I figured it out anyway.

Related

validation step by step

I have an aspx page with three textbox controls, and i want to do validation for all.
i want to show the error message in a sequence,
for example if i left all three text boxes empty and click on submit button,
first it will show error message for first text box and then when i fill the first textbox and click again save then it shows the error message for the second textbox and so on.
that means i only want to show one error message at a time after clicking the submit button.
can you people suggest me the way.
You could do it though checking on submission of the form and posting back to a literal with error messages. Postback validation is better than just relying on javascript in any case.
So, depending on the level of checks you want to employ, you could do something like:
protected void btnSubmit_Click(object sender, eventArgs e)
{
if(String.IsNullOrEmpty(txtBox1.Text))
{
ltError.Text = "Sorry, error message for box1";
return;
}
}
Obviously you'd work in more checks and after passing stage1 you'd move on to stage 2. Not great from a user experience but would work.
you can return a function value like this
public string CheckValidation()
{
if (txtFirstName.Text.Trim().Equals(string.Empty))
return "Please enter firstname";
if (txtLastName.Text.Trim().Equals(string.Empty))
return "Please enter lastname";
}
and so on as per your validation fields.
Hope this helps you
Can you use the AJAX control toolkit? The VaidatorCallout controls behave this way and you get a nice little balloon indicating where the error is.
ASP.NET Validator Callout
I'd recommend an <asp:CustomValidator> control for each textbox. You can use something like the following for the custom validation routines:
var textBox1IsValid = function textBox1IsValid(sender, args) {
var tb = document.getElementById('TextBox1'),
resultOfValidation = false;
//do validation, modifying resultOfValidation as needed.
arg.IsValid = resultOfValidation;
return resultOfValidation;
},
textBox2IsValid = function textBox2IsValid(sender, args) {
var tb = document.getElementById('TextBox2'),
resultOfValidation = false;
//do validation, modifying resultOfValidation as needed.
//return either the validity of TextBox2
//or (if TextBox1 is not valid) return true so the
//validator for TextBox2 doesn't fire.
arg.IsValid = resultOfValidation || !textBox1IsValid(sender, args);
return resultOfValidation;
},
textBox3IsValid = function textBox3IsValid(sender, args) {
var tb = document.getElementById('TextBox3'),
resultOfValidation = false;
//do validation, modifying resultOfValidation as needed.
//return either the validity of TextBox3
//or (if either TextBox1 or TextBox2 is not valid) return
//true so the validator for TextBox3 doesn't fire.
arg.IsValid = resultOfValidation || !textBox1IsValid(sender, args) || !textBox2IsValid(sender, args);
return resultOfValidation;
};
The advantage of this approach is that TextBox2 and TextBox3 will return as valid if their contents are valid or if TextBox1 is not valid. This will fire only one validator at a time, until all fields are valid. It's also a little more flexible as your custom validation routine can check for:
required field
pattern matching
value comparison
or any other validation that you need, all wrapped up into one function.
The downside is that you'll also need to duplicate the validation logic server-side.

why my view state not getting cleared and on reload it save the value to the databse again?

I am having user control registered on a aspx page.
there is a button on user control resisted on some aspx page that perform some action to store the value of viewste to the database, and below that i have cleared my viewstate value, but if i do right click and reload the page it reinsert the values to the data base, what i am missing or the viewstate do not get cleared, how should i prevent it to resave the same entries to the database.
I am partially writing my code below.
protected void btnFinish_Click(object sender, EventArgs e)
{
if (ViewState["dtQuestions"] != null)
{
foreach (DataRow dr in dtQuestions.Rows)
{
int currQueScore = GetAnswerScore(dr["AnswerType"].ToString().Trim(), dr["ClientAnswerValue"].ToString().Trim());
dr["ClientAnswerScore"] = currQueScore;
myScore += currQueScore;
SurveyClientAnswer objDetail = new SurveyClientAnswer();
objDetail.SurveyClientID = objMaster.SurveyClientID;
objDetail.QuestionID = int.Parse(dr["QuestionID"].ToString());
objDetail.Answer = dr["ClientAnswerValue"].ToString();
objDetail.Score = int.Parse(dr["ClientAnswerScore"].ToString());
DB.SurveyClientAnswers.InsertOnSubmit(objDetail);
DB.SubmitChanges();
}
objMaster.FinalScore = myScore;
DB.SubmitChanges();
ViewState["dtQuestions"] = null;
}
else
{
ModalPopupExtender1.Show();
pnl.Visible = true;
}
}
If you don't want to reinsert the data, simply create a unique constraint on the database to disallow this scenario.
As far as doing it in code, you could possibly only insert the data adding this condition to the if statement:
if(IsPostBack && (ViewState["dtQuestions"] != null)
{
//meaning the user is not simply reloading the page but actually posting back
}
Note that there might be some corner cases where this won't work. Without testing is difficult to know but I strongly believe that this should be handled at the database level instead.

asp:CustomValidator not returning 'false'

Don't know what is wrong here. This is a page developed by someone else and I am trying to fix one of the issue.
Scenario:
ASP.NET site.
Login.aspx has <asp:login> and there are three validation groups.
Login.aspx.cs is a partial class of "user_login".
Each validation group has a textbox and an associate customvalidator. All three custom validators gets triggered when something is entered in corresponding textbox but issue is only the first textbox (bound to validationgroup = 1) returns false when validation fails.
For 2nd and 3rd, the customvalidator get triggered but when there is validation issue and even after setting "args.IsValid = false;", the process continues with what needs to be executed further.
Don't know what is going on wrong here. I would like the customvalidator to return false. Worst case, are there any ways to return the control back to the 'textbox' when validation fails?
Below is the custom validator used.
<asp:CustomValidator ID="ExistingIdValidator" runat="server" ControlToValidate="NewUserName"
ValidateEmptyText="true" ValidationGroup="NewUserForm"
OnServerValidate="NewUserNameCheck_ServerValidate">
</asp:CustomValidator>
protected void NewUserNameCheck_ServerValidate(object source, ServerValidateEventArgs args)
{
CustomValidator validator = source as CustomValidator;
if (validator != null)
{
string NewuserNameValue = this.NewUserName.Text;
Guid registeredUserId = (Guid)Membership.GetUser(NewuserNameValue).ProviderUserKey;
if (registeredUserId != null)
{
validator.IsValid = false;
this.FailureText_New.Text = "This UserID already exists. Please login as existing user";
args.IsValid = false;
}
}
}
The funny thing about ASP.NET server-side validation is that it does not automatically prevent your click events from executing. It's as if the validation procedure is performed and then the results are ignored. So, the first thing to put inside your button's event is if (!Page.IsValid) return;. That's how you prevent the rest of the event from executing, and that's how you force the user to correct any mistakes on the form.

ASP.Net Control Visible=False Random Data Problem

Does anyone know of an issue with setting the Visible property of a control to false causing the value to change?
In the code below, the line:
control.Visible = dr.ParmDisplay;
On some servers, if the control is not visible it is not saving the value that was just set above it. We have a test server that this code works just fine, but we have a customer that the value is not saving. If the control is visible, it saves/shows/stores the value just fine on any server.
Is there some security patch that changes how this works??? I've Google'd it, and I don't find anything related to the visible property having this affect.
Here's the full code for this procedure:
protected void LoadReport()
{
dsReport.ReportParametersDataTable dt = objLoadXml.GetReportParameters(objReport.ReportName);
foreach (dsReport.ReportParametersRow dr in dt.Rows)
{
Control control = null;
IParm parameterControl = null;
if (dr.ParmType.ToUpper().StartsWith("DATERANGE"))
{
control = LoadControl("./UserControls/DateRange.ascx");
}
else if (dr.ParmType.ToUpper().StartsWith("DATE"))
{
control = LoadControl("./UserControls/Date.ascx");
}
else
{
control = LoadControl("./UserControls/Parameter.ascx");
}
control.EnableViewState = true;
parameterControl = (IParm)control;
parameterControl.ParmName = dr.ParmName;
parameterControl.ParmDescription = dr.ParmDescription;
parameterControl.ParmPickList = dr.ParmPickList.ToString();
if (dr["ParmDefaultValue"].ToString() != "")
parameterControl.ParmDefaultValue = dr.ParmDefaultValue;
control.Visible = dr.ParmDisplay;
PlaceHolder1.Controls.Add(control);
}
Thanks.
When you set a control to not visible, it does not get rendered to the browser. Therefore it will not be there on post back and the value won't make it back to the server.
If you need to persist the value w/out showing the control, store it directly in view state, or hidden input etc.

How do I check whether a DropDownList is initialized in ASP.NET?

How do I check whether a DropDownList is initialized in ASP.NET? I'm not talking about checking for empty strings. The dropdownlist is usually unintialized if there the datasource was not bound to it. So when I try to check the contents with something like this
x = DropDownList.SelectedItem.ToString()
it simply bombs...any suggestions?
You can check if the list has items:
if(dropDownList.Items.Count > 0) {
// do it...
} else {
// not initialized
}
If it's initialized it'll have items, if not it wont throw an error.

Resources