Get Hidden Field in Code Behind - asp.net

I have been looking at answers here and other places but so far have not found exactly how to do this.
I have the following definition for a hidden field in my .aspx page:
<asp:HiddenField ID="hfAddressChange" runat="server" />
I set the value in a javascript function on the client:
function confirmAddressChange()
{
if (typeof document.forms[0].hfAddressChange.valueOf ==="undefined")
{
var res = (confirm('"Update Contact Addresses to Rich?"')==true);
document.forms[0].hfAddressChange.valueOf = res;
}
}
Basically I only want to set the value once.
Now I want to check the value in the code behind:
If hfAddressChange.Value <> String.Empty Then
Dim x As String = "Do Something here"
End If
However, even though I have verified that the value IS being set in the js function, it is always an empty string when it gets to my code behind.
Anyone see what the heck I'm doing wrong?

document.forms[0].hfAddressChange.valueOf = res;
The property is value, not valueOf. (And it won't be undefined earlier, either; just check !document.forms[0].hfAddressChange.value.)

Related

pass control the value of input

Perhaps the topic name was chosen incorrectly, I will try to formulate my question. Is it possible to pass to the control an input value that has id = "dateToWork". Tried something like this
<CTR:datePickerKolibri3 ID="KolibriDatePicker1" runat="server" InToField="dateArrival" DayAfter=<% $(#dateToWork).val()%>/>
Hi to do what you want i think, me i create a usercontrol with the control and i add properties.
In your case i do that :
Create a new usercontrol
Add inside
In UserControl.ascx.designer set datePickerKolibri3 to public
Add in code behind of the USerControl :
Private p_datetowork As String
Public Property Datetowork As String
Get
Return p_datetowork
End Get
Set(value As String)
p_datetowork = value
End Set
End Property
And put your UserControl in the page you want and you can pass and access to the properties Datetowork
<CTR:UserControl ID="myUserControl" runat="server" Datetowork="my_date" >
or in Code behind :
myUserControl.Datetowork = "my_date"
If i underdstand your problem :D

User text box input is rewritten by default value

Consider the following .aspx page:
Title:
<asp:TextBox runat="server" ID="TitleTB"></asp:TextBox>
Details:
<asp:TextBox runat="server" ID="DetailsTB"></asp:TextBox>
<asp:Button runat="server" ID="Btn" Text="Submit" OnClick="Btn_click"/>
Note that I minimized the code to be legitimate so a lot of lines are missing (irrelevant lines, <br/> for example).
In the C# file, I usually post the details to the database (inserting them), but if I have a certain field in my query string (to_edit, per se) I need to update the, already existing, record.
Obviously, this task is overall simple. The thing is, that when that field is included, I initially (in the Page_Load event) set the Title and the Details fields to the values already found in the record (so the user won't have to input from zero, he'd have the ones he already entered to edit).
A debug would show, though, that when I post these back to the database (UPDATE query, which looks a bit like this UPDATE Table SET Title = #Title, Details = #Details WHERE ID=#ID, where I checked #ID - which is completely valid. #Title corresponds to TitleTB.Text and #Details to DetailsTB.Text, both added with SqlCommand.AddWithValue()) that DetailsTB.Text and TitleTB.Text are, for some reason, the same as I assigned them in the Page_Load although I deleted the whole text box content in my browser and refilled it with a different string.
Here are chosen parts of my Code Behind:
//A part of my Page_Load()
//reader is an SqlDataReader, the connection is valid, the values here are valid, and the output is as planned.
TitleTB.Text = (string)reader["Title"];
DetailsTB.Text = (string)reader["Details"];
And up to now, everything seems fine.
//Relevant parts of Btn_click()
cmd.Connection = conn; //valid connection
cmd.CommandText = "UPDATE QuestionsTable SET Title = #Title, Details = #Details WHERE ID=#ID";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Title", TitleTB.Text);
cmd.Parameters.AddWithValue("#Details", DetailsTB.Text);
cmd.Parameters.AddWithValue("#ID", Request.QueryString["to_edit"]);
conn.Open();
int affected = cmd.ExecuteNonQuery(); //affected is now 1, as expected.
conn.Close();
//There's a redirection over here.
But in the code shown above, TitleTB.Text and DetailsTB.Text are the same, it's not that the update query doesn't work. It's that, for some reason, the text boxes values won't change even when I clearly change them on my browser.
Any idea what could happen?
EDIT:
One remark is that when I use the OnClientClick event to alert the values (and then returning true, it was only for a test) - the values are identical to what I typed (not to the default value).
One of the possible reasons for such behavior is that you forgot to check if Page_Load is caused by a post back and you overwrite text both values in both get and post.
Just try to add an obvious condition:
//A part of my Page_Load()
//reader is an SqlDataReader, the connection is valid, the values here
if ( !this.IsPostback )
{
TitleTB.Text = (string)reader["Title"];
DetailsTB.Text = (string)reader["Details"];
}
Note that control values are stored in the viewstate and thus there is no need to update them during consecutive post backs.
Wrap your Page_Load event code in If(!IsPostBack){ }. The postback property of the button is refreshing the page with default value.
The code should be as follows -
If(!IsPostBack) {
//A part of my Page_Load()
//reader is an SqlDataReader, the connection is valid, the values here are valid, and the output is as planned.
TitleTB.Text = (string)reader["Title"];
DetailsTB.Text = (string)reader["Details"];
}
A good read may be helpful - http://www.codeproject.com/Articles/811684/Understanding-The-Complete-Story-of-Postback-in-AS

Why is the HiddenField value concatenating with the old value in asp.net?

Suddenly my application has some problems when getting the hiddenfield values on server side.
My Code that was running before this sudden event;
<asp:HiddenField ID="hfColumnName" runat="server" />
in the code behind I use to get and set its values like;
if(hfColumnName.Value == SortDirection.Ascending.ToString())
{
//have logic to perform.
hfColumnName.Value = SortDirection.Ascending.ToString();
}
else(hfColumnName.Value == SortDirection.Descending.ToString())
{
//have logic to perform.
hfColumnName.Value = SortDirection.Descending.ToString();
}
When next time this code runs, the hidden field value contains the concatenated values of its old and new one.
I faced the same issue. The root cause was html/asp code some improper tags. Please make sure the tag is proper.
http://forums.asp.net/p/1448466/3304601.aspx#3304601

Css the feedback label red or green depending on the outcome

I'm CSSing my project and would like to customize the font color for the feedback label. My project is built in 3 layers (DAL, BLL, normal page). In the BLL I catch exceptions and I guess this is where I would add the CSS stylesheet reference. Unfortunately, I can't get it to work, this is what it looks like.
BLL
Public Function deleteCustByCustID(ByVal CustID As Integer) As Boolean
If dataCust.DeleteCust(Cust) Then
Throw New Exception("The customer was removed.")
Return True
Else
Throw New Exception("The customer wasn't removed. Please try again.")
Return False
End If
End Function
ASPX.vb page
Try
bllCust.deleteCustByCustID(CustID)
Catch ex As Exception
lblFeedback.Text = ex.Message
End Try
I have my CSS pages stored in a CSS folder. I would like to assign the font color lime to a success and the font color red to a failure.
Any help is much appreciated!
Another option: if you have assigned an ID value to the markup for your "feedback" area, and if you added a runat="server" to that element, you can access the CssClass property in your code-behind file.
By way of example:
Markup
<div id="Feedback" runat="server"></div>
Code
Me.Feedback.CssClass="error"
Then you can use the CSS rules denoted by #rockerest in his answer.
EDIT:
Okay, I looked at your code again, and I see a big problem: you should NEVER use exceptions as a method of controlling program flow. That is probably error #1.
A not-too-uncommon method of returning a more meaningful result from your methods is to encapsulate a result object. Here is a simple example:
Public Class Result
Public IsValid As Boolean
Public Message As String
Public Sub New(ByVal isValid As Boolean, ByVal message As String )
IsValid = isValid
Message = message
End Sub
End Class
You would amend your current function to return a Result object instead of Boolean, and assign the values of the Result object depending on your query results:
Public Function deleteCustByCustID(ByVal CustID As Integer) As Result
Dim result as New Result
If dataCust.DeleteCust(Cust) Then
result = new Result( true, "The customer was removed." )
Else
result = new Result( false, "The customer wasn't removed. Please try again." )
EndIf
Return result
End Function
Then, in whatever code calls the deleteCustByCustID method, you assign the Message property to the content of the feedback area and the CssClass that matches the IsValid state.
Make sense?
EDIT 2:
Okay, assuming you have a CSS class for errors, ".error" and a CSS class for, uh, not errors, ".success". Then, let's pretend the following snippet was inside an event handler or somesuchthing:
Dim result As new Result = deleteCustByCustID( 42 )
Now you have a Result object that has a IsValid state value (it will be either true or false) and a Message string value. Your next step is to apply the message to the feedback element's (I'll assume here that you use an ASP.NET Label control) Text property, and then, based on the value of result.IsValid, assign the correct class to the label's CssClass property:
myFeedbackLabel.Text = result.Message
If result.IsValid Then
myFeedbackLabel.CssClass = "success"
Else
myFeedbackLabel.CssClass = "error"
EndIf
HTH.
The best answer here would be to define two classes in your main stylesheet like so:
.okay{
color: lime;
}
.error{
color: red;
}
And then simply set the correct variable in your BLL: "okay" for the first part of your if statement, and "error" for the else part. In the page, just use that variable as part of the class definition for the message:
Try
bllCust.deleteCustByCustID(CustID)
Catch ex As Exception
lblFeedback.Text = ex.Message
lblFeedback.cssClass = lblFeedback.cssClass + " " + [THE VARIABLE WORD HERE]
End Try
This should do what you're wanting.

ASP.NET EnqityDataSource WhereParameters, creates new property

I am trying to populate GridView, using EntityDataSource(code behind), I need to able to sort GridView. However when I sort i get error:
A property with name 'aspnet_Users.UserId1' does not exist in metadata for entity type
So I beleive it is because I generate where parameter in code behind:
ActiveEnqDataSource.WhereParameters.Add(new SessionParameter("aspnet_Users.UserId", TypeCode.Object, "UserName"));
Full code is :
ActiveEnqDataSource.ConnectionString = db.Connection.ConnectionString;
ActiveEnqDataSource.DefaultContainerName = "Entities";
ActiveEnqDataSource.EntitySetName = "Enquiries";
ActiveEnqDataSource.Include = "UserCars.CarModel.CarMake, Category, aspnet_Users";
ActiveEnqDataSource.EnableUpdate = true;
ActiveEnqDataSource.EnableInsert = true;
ActiveEnqDataSource.EnableDelete = true;
ActiveEnqDataSource.AutoGenerateWhereClause = true;
ActiveEnqDataSource.WhereParameters.Add(new SessionParameter("aspnet_Users.UserId", TypeCode.Object, "UserName"));
Any suggestions? Thank you very much! The gridview itself renders perfectly, only thing I cannot sort it, any "whereParameters" I add, Add 1 to the property e.g UserId1,EnquiryStatus1, ProdauctName1. etc...
I got a similar error because I was adding the where clause each time the page was posted back. Dropping my code that generated the where clause inside an IsPostback statement fixed the problem:
if (!IsPostBack) {
// code to add where parameters
}
I got the same error when I used markup to define a Where parameter AND then I added the same parameter in code. Somewhere along the line, the 1 at the end of the parameter name was added.

Resources