textBox losing values on postback? - c#

I have asp.net page (Form = runat server )
2 textboxes:
<input type="text" id="tb1" />
<asp:TextBox ID="tb2" runat="server" />
and a button submit.
However when I put some values in them - and press the button - Only tb2 is getting back its value from the server.
I thought that inputs fields values are going from client to server and back always !
in what event ( in page life cycle) Does tb1 lose its value ?

<input type="text" id="tb1" /> is literal HTML.
There is no server-side code that puts the value back in.
That feature is part of server-side controls.

The POST will contain information entered in tb1 - so it can be read from the Request
if you change it to
<input type="text" id="tb1" runat="server" />
it will work as you want.
without the runat=server it does not "lose" its value - it will never be populated - ever, because it is simply data in the POST and not connected to a server side control.
one final point - to explicitly answer some of your comments - the POST data is processed just before the PreLoad event - this can be found from http://msdn.microsoft.com/en-us/library/ms178472.aspx

tb1 is not a server side control, it is a normal html dom object.
You should find its value after a post in the Request.Form value collection however.

Related

ASP.NET C# client-side & server-side validation with regular expressions

I have a pretty straightforward aspx form that collects name, address, email etc and I'm trying to do server-side validation using asp controls. It's working (I think?) and I know I need to do it server-side, but I'm not sure exactly where to put the regex for the actual requirements for each field.
Here's one of my fields as an example:
<div class="form-group">
<asp:Label runat="server" AssociatedControlID="FirstName" CssClass="col-md-2 control-label">* First Name</asp:Label>
<div class="col-md-3">
<asp:TextBox runat="server" ID="FirstName" CssClass="form-control" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="FirstName"
CssClass="text-danger" ErrorMessage="First Name field is required." Display="Dynamic" />
</div>
</div>
I've been using an asp:RequiredFieldValidator and the client-side validation part is working perfectly. The form knows when the user has or hasn't entered something into my required fields and notifies them accordingly before sending anything to the server. I've tested it by putting a label on my page called "valid" and then putting this into my submit button click event:
if(Page.IsValid)
{
valid.Text = "it's working";
}
And when I fill out the required fields my label does indeed appear and say it's working. However, the asp:RequiredFieldValidator, by definition, only indicates whether my required fields have a value of some kind. It does nothing to check the formatting of what the user entered.
I do need to make certain fields required and I like how the client-side validation part is working. But I also need to do server-side validation and use regex somewhere in the mix to make sure they actually entered an e-mail address in the e-mail field and actually put numbers in the zip code field etc.
I'm fairly new to ASP.NET and it's starting to feel like I'm fighting it. I don't want to fight it. I want to use the available tools to do pretty standard server-side validation, I'm just not exactly sure where to put the regex.
Can anyone help?
Thanks
Web Forms validators add client and server side code automatically to cover both bases. In the case of your RequiredFieldValidator, it simply checks the value is present on the client and if you also call "Page.IsValid" when Page_Load is fired it will do so on the server end.
What you are after is the "RegularExpressionValidator". You can use one or both on the page depending on what you are trying to achieve.
Here's a good example: https://msdn.microsoft.com/en-us/library/ff650303.aspx
You can write your own validator, client and server side. Check out
CustomValidator
Example:
<asp:CustomValidator runat="server" id="CustomValidator" ValidateEmptyText="false" OnServerValidate="customValidation_event" ClientValidationFunction="customValidation_client" />
And add javascript function and validation method in your code-behind.

Save the data values from jQuery textbox

I am working on an asp.net page where I am saving user input into my database using TextBox e.g ***<asp:TextBox ID="code" runat="server" Width="155px"></asp:TextBox>***
in this case I'm getting the ID of the TextBox as "code" so i can capture the values from that TextBox. Now i have a jQuery texbox <input type="text" id="date" required="required"/> where "date" is jQuery function ID. Which attribute or ID should i use to capture the user input and save them into my database using this <input type="text" id="date" required="required"/> textbox..?
you can change your plain textbox to asp textbox
<asp:TextBox Id="date" runat="server" required="required" />
if not than you can get values of plain Html elements in code behind.
Write a function to set the value of "date" textbox to a hidden
field
Than capture the value of hiddenfield in your code behind
Hope this helps
Why not simply turn that field into a asp.net control as well?
Would be:
<asp:TextBox Id="date" runat="server" required="required" />
It will be rendered as a input type="text" to the browser anyway and should work just fine.
In order to find the control (since ASP.NET sometimes have the odd interest in prefixing controls) you can just use $find in your script. Or, as someone pointed out, use class selectors (i.e assign a CssClass attribute to your TextBox) and use that as selector in your jQuery code.
That way the date value will be available both to server side operations and client side.
you can use Asp.Net textbox as jquery datepicker, just use class selector to convert into jquery ui date picker

ASP.NET - Using SagePay Form Method Within a Content Page

I have an ASP.NET site and need to post some hidden form fields to SagePay so that my customers can pay for goods. I am using the following method to do this:
<input type="hidden" name="VPSProtocol" value="2.23" />
<input type="hidden" name="Currency" value="gbp" />
<input type="hidden" name="TxType" value="PAYMENT" />
<input type="hidden" name="Vendor" value="myvendorname" />
<input type="hidden" runat="server" id="crypt" name="Crypt" value="#<encrypted string>" />
<asp:Button ID="Button1" runat="server" Text="Pay Now" PostBackUrl="https://live.sagepay.com/gateway/service/vspform-register.vsp"/>
Now, If I use this code in a standard ASP.NET form, this works fine - SagePay accepts the posted information and continues with the payment process. However, if I use the same code inside a content page with a master page, Sagepay displays the following error screen:
5030 : We could not process your message, please check your
integration settings or contact the support team.
It seems as if the hidden fields are losing their value because of the master page.
Could anyone tell me what could be happening here and if there is anything I can do to rectify the situation. I need to use the SagePay Form method and I need to use a masterpage.
I haven't used webforms for a while but from memory by default it changes the names of your elements based on their container to allow navigation and identification server side: MSDN documentation here.
This means that your posted values are not under the name you expect them to be.

Reset a page in ASP.NET without postback

I want to reset a form but I'm using a few "Required Field Validator" every time I click the reset button the error message shows requiring fields... What I tried:
ReuiqredFieldValidator.Enabled = false;
TextBox.Text="";
Response.Redirect("Samepage.aspx");
Response.Redirect("Request.RawUrl");
<input type=reset>
Try this:
<asp:Button
runat="server"
ID="reBt"
Text="Reset"
OnClientClick="this.form.reset();return false;"
CausesValidation="false"
/>
from here
You can apply ValidationGroup property to group of controls and the relevant asp button and do not provide ValidationGroup to reset button.
Or same can be achieved vice-versa
This is applicable as you using asp.net controls
Refer this link
you can try it
<input type="reset" causesvalidation="False">
It should work.
It works for input submit so I think it should work on input reset also.
Details Input =submit
Edit 1
Or if you are using jQuery you can use like this
$(':input','#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
References
Clear form fields with jQuery
How to reset a form using jQuery with .reset() method
jQuery reference
:reset Selector

ASP (.NET 4) ViewState enabled Literal control not retaining changes to HTML contents on PostBack

I am populating a ListView with HTML from a database using a Literal with Text='<%#Eval("HTMLData")'%>. When I trigger a PostBack, changes to the loaded HTML are not being reflected in litRowData.Text.
ViewState is enabled for the page, the ListView, and the Literal in the ItemTemplate, and I am making sure to only populate the ListView with initial values from the database when if(!IsPostBack) is true in Page_Load.
<asp:ListView ID="lvForm" runat="server"
DataKeyNames="RowID" ItemPlaceholderID="phRow"
EnableViewState="true">
<LayoutTemplate>
<asp:PlaceHolder ID="phRow" runat="server" />
</LayoutTemplate>
<ItemTemplate>
<asp:Literal ID="litRowData" runat="server" Text='<%#Eval("HTMLData")%>'
EnableViewState="true"></asp:Literal>
</ItemTemplate>
</asp:ListView>
I need to be able to capture changes to the contents of the loaded HTML controls. Since this HTML comes from a database table, I can't just use ASP controls inside the ItemTemplate. Can anyone see something I'm missing, or suggest an alternative way to do this?
Edit:
To clarify a little more, I'm trying to load form input elements dynamically from a database, render them as HTML controls on the page, allow the user to modify their contents by entering text or selecting options, then capture the modified HTML and save it back to the database when the user clicks a save button.
The way postback works in .NET is actually a wrapper around the more basic idea of HTML forms. A basic example of HTML forms is:
<html>
<body>
<form action="" method="POST">
<input type="text" value="type here" />
<input type="submit" value="go" />
</form>
</body>
</html>
Roughly, what the .NET abstraction adds is:
<html>
<body>
<form action="" method="POST">
<input type="hidden" name="__VIEWSTATE" value="string-encoded-value" />
<input type="text" name="bob" value="type here" />
<input type="submit" value="go" />
</form>
</body>
</html>
Whereby on postback to your page, all input elements with names are mapped back into properties of your Page object, and the __VIEWSTATE hidden field is deserialized into all properties of objects that do not correspond to values of html input tags. For example, if Page.bob had a DateTime property associated with it, it would be stored in __VIEWSTATE possibly.
ASP.NET Literal tags in Page markup will get printed into the browser exactly as is, meaning that if you have <span>bob</span> as its value, that is how it will appear within the <form> tag. However, in plain HTML world, <form> tags when posted will only contain the values of certain form elements (aka not every div, span, p etc. gets posted back, only input, select, textarea and some others). So if your literal doesn't contain an input then it won't even get posted back meaning __VIEWSTATE will be used to restore the Value property of the Literal back to its initial state.
To fix this, you probably don't want to stick html into a Literal because even if you do it's not clear that it will get associated with the right property of your page. Instead, try a TextBox element or something else that gets written as an input element directly by the ASP.NET webforms code. Alternatively, try using javascript to allow modifications of flat text in divs if you don't need to persist the data.
This answer builds on the prior one now that you have a .NET TextBox control that is correctly posting back the value of edits. Right below it, you can add to code behind:
protected void Page_Load(object sender, EventArgs e)
{
litRowData.Attributes.Add("onKeyUp", "WriteText(this.value)");
}
Html:
<ItemTemplate>
<asp:TextBox ID="litRowData" runat="server" />
</ItemTemplate>
<div id="yourPreview"></div>
<script type="text/javascript">
function WriteText(val){
document.getElementById("yourPreview").innerHTML=val
}
</script>

Categories

Resources