Validating a .NET 2.0 form with JQuery Validate() issues - c#

I am trying to validate a form in .NET 2.0 using the JQuery Validate() plug-in and it’s not working. I know my Jquery code is working as I set up functions to clear the default text of a text field on focus() and that works as expected.
The form.validate() method never seems to get called as I have alert() calls in a custom validation method that work in a separate HTML test page but never fire when integrated into the .NET page.
Could this be because the whole page is treated like a form in .NET? If I want to override the default submit action and add some client side validation, how can I do this or can I only validate the form in the code behind? Thanks.
my script:
<script src="js/jquery.validate.min.js" type="text/javascript"></script>
<script src="js/additional-methods.js" type="text/javascript"></script>
<script src="js/jquery.maskedinput.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
jQuery.validator.addMethod("checkfields", function(value, element) {
if ($("#from_date").val() == "" && $("#to_date").val() == "" && $("#last_name").val() == "") {
return false;
}
}, "Please enter either a last name, from date or to date.");
$("input.from_date").mask("99/99/9999");
$("input.to_date").mask("99/99/9999");
$("#searchForm").validate({
errorElement: "span",
errorContainer: $("#error"),
errorPlacement: function(error, element) {
error.appendTo(document.getElementById("error"));
},
success: function(label) {
$("#searchForm").submit();
},
rules: {
last_name: "checkfields"
}
});
$("#from_date").focus(function() {
if ($("#from_date").val() == "mm/dd/yyyy") {
$("#from_date").val("");
}
});
$("#from_date").blur(function() {
if ($("#from_date").val() == "") {
$("#from_date").val("mm/dd/yyyy");
}
});
$("#to_date").focus(function() {
if ($("#to_date").val() == "mm/dd/yyyy") {
$("#to_date").val("");
}
});
$("#to_date").blur(function() {
if ($("#to_date").val() == "") {
$("#to_date").val("mm/dd/yyyy");
}
});
});
</script>
And the form:
<form action="search.spax" id="searchForm" name="searchForm" method="post">
<div id="error" style="display:none;">
<span></span>.<br clear="all"/>
</div>
<table width="520" border="0" cellspacing="0" cellpadding="0" class="obit_form">
<tr align="left">
<th><label for="last_name">Last Name</label></th>
<th></th>
<th><label for="from_date">From</label></th>
<th><label for="to_date">To</label></th>
<th></th>
</tr>
<tr align="left">
<td><input type="text" id="last_name" class="required date" name="last_name" value="" style="width:135px;" /></td>
<td>and/or</td>
<td><input type="text" id="from_date" class="required date" name="from_date" value="mm/dd/yyyy" style="width:75px;" /></td>
<td><input type="text" id="to_date" class="required date" name="to_date" value="mm/dd/yyyy" style="width:75px;" /></td>
<td><input type="submit alt="Search" title="Search" value="Search" name="submitButton" id="Submit2" /></td>
</tr>
</table>
</form>

You're doing something like this?
$(document).ready(function() {
$('#aspnetForm').validate({
rules: {
ctl00$chMain$tbLoginEmail: {
required: true,
email: true
},
...
I know hard-coding the id isn't ideal, but you get the picture.

Related

what is difference between POST Method from Client Side html and Server Side C#

html Post Method
<script type="text/javascript">
function submitdata() {
document.tp_form.submit();
}
</script>
<form name="tp_form" action="someurl" method="post" id="form_id">
<table>
<tr>
//// In td i send all the same parameter as which send from C#
<td>User ID : <input type="text" name="user_id" value="test"><br></td>
<td>Order No : <input type="text" name="order_no" value=""></td>
</tr>
<tr>
<td><input type="button" name="hash" value="hash" onClick="submitdata();" > </td>
</tr>
</table>
</form>
C# Post Method
NameValueCollection collections = new NameValueCollection();
collections.Add("user_id", api3.user_id);
collections.Add("order_no", api3.order_no);
collections.Add("pay_type", api3.pay_type);
collections.Add("good_name", api3.good_name);
collections.Add("trade_mony", api3.trade_mony);
collections.Add("order_first_name", api3.order_first_name);
collections.Add("order_email", api3.order_email);
collections.Add("currency", api3.currency);
collections.Add("site_cd", api3.site_cd);
collections.Add("hash_data", api3.hash_data);
string html = "<html><head>";
html += "</head><body onload='document.forms[0].submit()'>";
html += string.Format("<form name='PostForm' method='POST' action='{0}'>", apiurl);
foreach (string key in collections.Keys)
{
html += string.Format("<input name='{0}' type='hidden' value='{1}'>", key, collections[key]);
}
html += "</form></body></html>";
Response.Clear();
Response.Write(html);
When I do Post From HTML it is redirected to Payment Page But when I am doing from C# it is not redirecting it is giving me error.In Both case parameters are same.
What is the difference in both way i.e HTML and C#

How do I pass an HTML element's value to a C# code-behind method?

For example, right now I have my ASPX like so:
<form name="form" runat="server" onsubmit="validate(this)">
<table width="100%" height="100%">
<tr>
<td class="label">
Start Date:
</td>
<td>
<input type="text" name="StartDate" value='<%=GetCurrentDate("- testParam")%>' maxlength="10" />
</td>
</tr>
</table>
</form>
..and my C# as follows:
public static string GetCurrentDate(string str)
{
return DateTime.Now.ToString("MM/dd/yyyy") + str;
}
This works fine and outputs "03/08/2017 - testParam". But what if, for example, instead of sending a hardcoded string manually as I did above, I want to pass in one of the HTML element's values as a parameter from the ASPX side? Like this:
...
<tr>
<td class="label">
Start Date:
</td>
<td>
<input type="text" name="StartDate" value="<%=GetCurrentDate(formObj.elements.item('someLabel').value)%>" maxlength="10" />
</td>
</tr>
...
What do I need to do to get the "someLabel" element's value on my ASPX page to the C# page? Any help with this will be greatly appreciated.
If you want to pass a value from client-side to code behind without posting back the entire page, you will need to use Ajax.
Calling to a server-side method in ASP.Net Web Form is not as clean as ASP.Net Web API or MVC. You will need to use old WebMethod.
For example,
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DemoWebForm.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<button type="button" onclick="getData();">Get Data</button>
<br/>
<input type="text" name="StartDate" id="txtStartDate" maxlength="10" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
function getData() {
var data = {value: "test"};
$.ajax({
type: "POST",
url: '<%= ResolveUrl("~/Default.aspx/GetCurrentDate") %>',
data: JSON.stringify(data),
contentType: "application/json",
success: function (msg) {
$("#txtStartDate").val(msg.d);
}
});
}
</script>
</form>
</body>
</html>
Code Behind
using System;
using System.Web.Script.Serialization;
namespace DemoWebForm
{
public partial class Default : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static string GetCurrentDate(string value)
{
return new JavaScriptSerializer().Serialize(
string.Format("{0} - {1}", DateTime.Now, value));
}
}
}
this method GetCurrentDate running server side but this formObj.elements.item('someLabel').value running on client
try this..
<tr>
<td class="label">
Start Date:
</td>
<td>
<input type="text" name="StartDate" value='<%=GetCurrentDate()%>' maxlength="10" />
</td>
public string GetCurrentDate()
{
return DateTime.Now.ToString("MM/dd/yyyy");
}
for read value of input named as StartDate from server..
string postValue = Request.Form["StartDate"]
You can make it a server control by adding runat="server" and it will be available in your code behind file. OR if you don't prefer this then use Request.Form["Name"] in your code behind file. Here "Name" is the name you are giving to your textbox control.
In your case the name is StartDate
So try to access the value of textbox from the code behind using Request.Form["StartDate"]
Read this article.. https://www.aspsnippets.com/Articles/Get-value-of-HTML-Input-TextBox-in-ASPNet-code-behind-using-C-and-VBNet.aspx
You should post value you want to send to the webserver into an html form.

Check html field hidden or not using C# backend code

I have the following code in which I am showing and hiding html controls based on Dropdown list selected value. Show and Hide is working fine but I want to Check in backend i.e C# that the which <tr> is visible and which one is hidden.
Here is my aspx page code
<script type="text/javascript">
$(document).ready(function () {
$("#AttachemntType").change(function () {
if ($(this).val() == "F") {
$("#tr_CompileFile").show();
$("#tr_SourceFile").show();
}
else if ($(this).val() == "R") {
$("#tr_CompileFile").hide();
$("#tr_SourceFile").show();
}
else {
$("#tr_SourceFile").hide();
$("#tr_CompileFile").hide();
}
});
});
</script>
<tr bgcolor="white">
<td style="height: 20px">
Attachment Type
</td>
<td>
<select id="AttachemntType" name="AttachemntType" style="width: 344px">
<option value="0">Select</option>
<option value="F">Form</option>
<option value="R">Report</option>
</select>
</td>
</tr>
<tr bgcolor="white" id="tr_SourceFile" style="display:none;" runat="server">
<td style="height: 20px">
Source File
</td>
<td>
<input class="body_text" type="file" id="src_File" name="src_File" runat="server"
style="width: 420px" />
</td>
</tr>
<tr bgcolor="white" id="tr_CompileFile" style="display:none;" runat="server">
<td style="height: 20px">
Compiled File
</td>
<td style="height: 16px; width: 625px;">
<input class="body_text" type="file" id="comp_File" runat="server" style="width: 420px" />
</td>
</tr>
This is the code which I am trying in Backend but its returning always true for all fields
if (tr_CompileFile.Visible == true && tr_SourceFile.Visible == true)
{
//This Condition is always true
}
else if (tr_SourceFile.Visible == true && tr_CompileFile.Visible == false)
{
//something
}
else
{
//something else
}
You cannot actually check this in backend. .show() and .hide() are jQuery methods which only operates on client side.
One workaround could be to use a MVVM pattern with knockout.js (Don’t try angular for that, you’ll be lost in docs)
Another option is to actually put your select box and the hidden/visible parts into UpdatePanel. So when you change the selector, the server side is called and you can assign / remove “visible” field.
More : https://msdn.microsoft.com/en-us/library/bb399001.aspx
In last resort, you can put a hidden field, which will be populated on submit with “hidden,shown,etc” values for you inputs.
Personally, I’ll vote for the first, but second is the easiest one to implement
Yes, Jurion was right. just adding more explanation: you can try
tr_CompileFile.Style["HTML Style key here"]
for example you can try
tr_CompileFile.Style["display"]
but it will return to you the value of the particular style defined in your aspx files, not the actual style displayed and changed in client side.
If you defined
<asp:Button ID="btnTest" runat="server" style="display:none" />
when you check it,
btnTest.Style["display"]
will return "none"

How to handle checkbox item when using FormCollection using same name in asp.net mvc?

I have to get the checkbox form collection as bool value array to insert into bit datatype column in SQL Server. I tried the below thing with partial luck.
If all the checkboxes are checked, It is working fine. But If some left as unchecked only the checked items are in array. So the index varies and could not identify which belongs to which record?
Please help me.
string[] names = Students["name"].Split(char.Parse(","));
string[] dnos = Students["dno"].Split(char.Parse(","));
string[] adds = Students["address"].Split(char.Parse(","));
string[] actives = Students["active"].Split(char.Parse(","));
for (var i = 0; i < names.Length; i++)
{
student stds = new student();
stds.name = names[i];
stds.dno = dnos[i];
stds.address = adds[i];
if (actives[i] == "on")
stds.active = true;
else
stds.active = false;
db.students.AddObject(stds);
}
db.SaveChanges();
HTML:
#model DynamicAddition.DAL.student
#{
ViewBag.Title = "Create";
}
<h3>Create</h3>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<form id="formstudent" method="post">
<table id="formTable">
<thead>
<tr><th>Name</th><th>D. No</th><th>Address</th><th>Active</th><th>Add New</th></tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="name" /></td>
<td><input type="text" name="dno" /></td>
<td><input type="text" name="address" /></td>
<td><input type="checkbox" name="active" /></td>
<td><b>Add new</b></td>
</tr>
</tbody>
</table>
<p><input type="submit" value="Create" /></p>
</form>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
<script src="../../Scripts/jquery-1.5.1.js"></script>
<script language="javascript" type="text/javascript">
function addRow() {
$('#formstudent tbody tr:first').clone().find("input").each(
function () {
$(this).val = '';
}).end().appendTo("#formTable");
}
</script>
i stumbled to the same problem while creating a dynamic form.
going by the html standards there are some controls that are posted back and some that are not. So a checkbox that is not checked or an input that is disabled isnt posted back to the server on a form postback.
The normal practive to handle these situations is to make a hidden input with the default value in you case since the default value is false make a input
#Html.Hidden("name1",..)
and set the value as false
then using the same name as of this input make a checkbox
#Html.Checkbox("name1", ..)
by doing this even if the checkbox isnt checked the value of the hidden input will be posted back to the server and you will get a valid false value.
**Note :- Asp.net MVC uses same trick whenever is needs a value postback.
**Note:- there is already an answer depicting this nicely how to POST/Submit an Input Checkbox that is disabled?

How can I make a "tr" of a table visible using JavaScript for a checkbox event?

I have a checkbox when user checked that check box means. I need to make this tr visible "true" on the page. If again unchecked make tr "invisible" using JavaScript or jQuery.
Initially during the page load I have binded the values for the drop down
<tr id ="trddl" runat= "server" visiable="false">
-- here I have a dropdown control where values are coming from DB --
</tr>
Right now I am doing using server side event for the check box, which takes a lot of time.
if(chkbox.checked=true)
{
trddl.visiable= true
}
This should help you:
<html>
<head>
<script language="javascript">
function Toggle(sender)
{
document.getElementById('theRow').style.display = sender.checked?"block":"none";
}
</script>
</head>
<body>
<input type="checkbox" checked="checked" onclick="Toggle(this)" /> Show Row
<table>
<tr id="theRow"><td>Test Row</td></tr>
</table>
</body>
</html>
The row:
<tr id="tr99"><td>......</td></tr>
The checkbox:
<input type="checkbox" onclick="toggletr(this);" value="val" id="cbox" />
The javascript:
<script type="text/javascript>
$(document).ready(function() {
//$(#tr99).hide(); //ver 1
toggletr($(#cbox)); //ver 2
});
function toggletr(obj){
if(obj.checked)
$(#tr99).hide();
else
$(#tr99).show();
}
</script>
<input type="checkbox" name="cb1" id="cb1">
<table>
<tr id="row1">
<td>...</td>
</tr>
</table>
with
$(function() {
var cb1 = $("#cb1");
cb1.change(toggle_cb1);
// this sets 'this' to the checkbox
// note: this is only required if you don't hide or show the row
// correctly on the serverside based on the checkbox state
toggle_cb1.call(cb1[0]);
});
function toggle_cb1() {
if ($(this).is(":checked")) {
$(this).show();
} else {
$(this).hide();
}
}
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
//We attach an "onclick" event handler to our 1st checkbox here, as apposed to html code below for the input checkbox
//This is the practice of separating display vs function
$("#chkToggle1").click(function(){
//Call our toggleVisibility JS function, passing in a jQuery object for the row we want to hide, and a boolean indicating if our checkbox is checked or not
toggleVisibility($("#trTarget1"), $(this).is(":checked"));
});
//Again for our 2nd checkbox
$("#chkToggle2").click(function(){
//Call our toggleVisibility JS function, passing in a jQuery object for the row we want to hide, and a boolean indicating if our checkbox is checked or not
toggleVisibility($("#trTarget2"), $(this).is(":checked"));
});
//Again for our 3rd checkbox
$("#chkToggle3").click(function(){
//Call our toggleVisibility JS function, passing in a jQuery object for the row we want to hide, and a boolean indicating if our checkbox is checked or not
toggleVisibility($("#trTarget3"), $(this).is(":checked"));
});
});
//I created a generic function that can reused for toggle visibility of other objects, not locked down to just our table row
//You'll note the first parameted has a "$" before it. This is to denote that the function is expecting a jQuery object and not a normal DOM object
function toggleVisibility($targetObj, isVisible){
if(isVisible == true)
$targetObj.show();
else
$targetObj.hide();
}
</script>
<head>
<body>
<input type="checkbox" id="chkToggle1" checked="checked" />
<input type="checkbox" id="chkToggle2" checked="checked" />
<input type="checkbox" id="chkToggle3" checked="checked" />
<table style="border: 1px solid black;">
<tr id="trTarget1">
<td>Table Row 1</td>
</tr>
<tr id="trTarget2">
<td>Table Row 2</td>
</tr>
<tr id="trTarget3">
<td>Table Row 3</td>
</tr>
<table>
</body>
</html>

Categories