I have some fields in a repeater and I need to validate them.
Here is the scenario:
When the page loads I get a set of fields just once(first name, last name etc.) and I get a link "Add another user", if you click the link it adds the same fields again on the bottom.
Now for the code part:
In my case I needed to run the repeater 4 times (so the fields are on the page 4 times from the begining). Then I hide them as I hide the <div> that contains them. When the button is clicked I show the first hidden div and so on.
Some code(not all):
<asp:Repeater ID="rptOtherPeople" runat="server">
<HeaderTemplate>
<table>
<thead>
<tr>
<td>
<h3>Други лица</h3>
</td>
</tr>
</thead>
<tbody class="GridBody">
</HeaderTemplate>
<ItemTemplate>
<tr class="GridRow" id="personRow" style="display: none">
<td>
<asp:TextBox ID="txtFirstName" CssClass="mid-inp" Text="" runat="server"></asp:TextBox>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</tbody>
</table>
</FooterTemplate>
</asp:Repeater>
And here is that javascript that shows the next row:
$(document).ready(function () {
var peopleNum = 1;
if ($(".GridBody tr").length > 0) {
var tr = $(".GridBody tr")[0];
tr.style.display = 'table-row';
tr.setAttribute('hidden', 'false');
var anc = tr.getElementsByTagName('a');
}
if ($(".GridBody tr").length > 0 && peopleNum > 0) {
for (i = 0; i < peopleNum; i++) {
var tr = $(".GridBody tr")[i];
tr.style.display = 'table-row';
tr.setAttribute('hidden', 'false');
if (i > 0) {
var anc = tr.getElementsByTagName('a');
if (anc[i] != undefined)
anc[i].style.display = 'none';
}
}
}
})
function addPerson() {
var body = $(".GridBody");
var indexOfNextRow = $('tr[class="GridRow"][hidden="false"]').length;
var tr = $(".GridBody tr")[indexOfNextRow];
tr.style.display = 'table-row';
tr.setAttribute('hidden', 'false');
}
The Problem: For example I want the field to be required. I put a RequiredFieldValidator and I disable it in some cases and enable it in others. The thing is that I get 4 RequiredFieldValidators on the page and I can only turn ALL of them on or off at once. I want to activate just one of them. I couldn't find a way to do that because they are pretty much identical. Any ideas?
I assume that I can not sort this out in the code behind. Can I work with just one RequiredFieldValidator via javascript(how do I identify the one I want).
Some people prefer jquery validation. Is it applicable in this case and how(I have never used jquery validation before)?
EDIT 1
Ok the controls are not identical. In the browser the generated ID is: ctl00_SPWebPartManager1_g_f6926ea5_98ba_46c1_b157_4f1ddc46885d_ctl00_Step21_otherPeople_rptOtherPeople_ctl01_rv1 , but I can not access the validator from here in my Javascript
You can disable the validators either server side or client side.If i understood your question , the thing you looking for is disabling a specific vaidator say required field validator.For that here is a simple javascript code to disable the validators.
function DisableRFValidators() {
var ValidatorToDisable = document.getElementById("RequiredFieldValidator2");
ValidatorEnable(ValidatorToDisable, false);
}
Fixed it! Here is the code:
$("#aspnetForm").validate();
$(".required").each(function (index) {
if ($(this).attr("id").indexOf("txtFirstName") >= 0) {
$(this).rules("add", {
required: true,
minlength: 3,
messages: {
required: "<div class='val' style='color:red'>Name is Required!</div>",
minlength: "<div class='val' style='color:red'>Minimum number of symbols = 3!</div>"
}
});
}
else if ($(this).attr("id").indexOf("txtFirstName") >= 0){
$(this).rules("add", {
required: false
});
}
});
function validateData() {
var result = $("#aspnetForm").valid();
return result;
}
function btnNextClick(btn_this) {
var btnNext = document.getElementById("<%=btnMoveNextHidden.ClientID%>");
if (btnNext != null && validateData() == true) {
btnNext.click();
}
}
Related
Basically I want my code to update the textarea as users put a check in a checkboxes inside a table. If a checkbox is checked, a username will be placed in textarea along with line breaks. If unchecked, it will remove from textarea. After that, a button will submit every string inside the textarea.
#using (Html.BeginForm())
{
#Html.AntiForgeryToken();
<td align="center">
<form>
<div style="max-width:50%" class="form-group #if (ViewBag.ErrorMessageDelete != null)
{ <text>has-error</text> } ">
#Html.TextArea("deleteRequest", string.Empty, 5, 100, null)
#if (ViewBag.ErrorMessageDelete != null)
{
<span class="help-block">#ViewBag.ErrorMessageDelete</span>
}
</div>
<button class="btn btn-primary" onclick="return confirm ('Removing these members, are you sure?')">Remove User(s)</button>
</form>
</td>
}
and this is my current checkbox
<td align="center" style="width:5%">
#Html.CheckBox("toBeDeleted", new { onclick = "deleteRequest = deleteRequest + item.username + <br>" });
</td>
I used textarea because I want users to be able to input usernames on their own without using checkboxes. Is it possible to do it in MVC ASP.NET in Visual Studio?
Don't do this with click event. Use change event on checkbox.
You can also try with the array. If the checkbox is checked add item to array, if not remove it. After that convert array to string, and set a value to textarea. Delete and push logic you have to implement by your own.
<td align="center" style="width:5%">
#Html.CheckBox("toBeDeleted", new { onchange="testfunc(this)", data_username = item.username });
</td>
<script>
var result = [];
function testfunc(elem) {
var username = $(elem).attr("data-username");
if($(elem).is(':checked')) {
result.push(username )
}
else{
var index = result.indexOf(username);
if (index > -1) {
result.splice(index, 1);
}
}
$("#deleteRequest").val(result.join("\n"));
}
</script>
I have form which was built on Asp.Net platform. This form works as expected whe we enter entry as text for both Country and State and I can submit the data to the database. Now I need to change the code with the logic to have drop down for Country and State. Example: If United States is selected it shows related states and user need to select the entry from drop down and submit the form and it should save it in database. I haven't changed anything in code behind in the working code, just adding the list drop down instead of Text entry for both Country and State. I am getting error "Invalid postback or callback argument" when I click the Submit button for submission. I have included the working code with text box entry and the change I have done by replacing with the list drop down. I have also included the error detail I am getting. Looking at other postings on stackoverflow, I added enableEventValidation="false" in .aspx page, but it didn't solve the issue. Any idea how can I resolve this?
.aspx Code with Text box field: (This is working)
<tr>
<td><div align="right"><span class="style4">*</span> State:</div><asp:RequiredFieldValidator id="reqstate" ControlToValidate="state" ErrorMessage="Required Field!" runat="server" /></td>
<td><asp:TextBox runat="server" name="state" type="text" id="state" size="30" /></td>
</tr>
<tr>
<td><div align="right"><span class="style4">*</span> Country:</div><asp:RequiredFieldValidator id="reqcountry" ControlToValidate="country" ErrorMessage="Required Field!" runat="server" /></td>
<td><asp:TextBox runat="server" name="country" type="text" id="country" size="30" /></td>
</tr>
Changed .aspx Code with List Drop Down: (This is not working)
<tr>
<td><div align="right"><label id="stateLabel" style="display: none"><span class="style4">*</span> State:</label></div><asp:RequiredFieldValidator id="reqstate" ControlToValidate="state" ErrorMessage="Required Field!" runat="server" /></td>
<td><asp:ListBox name="state" id="state" style="display: none" rows="1" runat="server"></asp:ListBox></td>
</tr>
<tr>
<td><div align="right"><span class="style4">*</span> Country:</div><asp:RequiredFieldValidator id="reqcountry" ControlToValidate="country" ErrorMessage="Required Field!" runat="server" /></td>
<td>
<asp:ListBox id="country" onchange="javascript:countryChange()" rows="1" runat="server">
<asp:ListItem selected="false">Select Country</asp:ListItem>
<asp:ListItem>United States</asp:ListItem>
<asp:ListItem>Canada</asp:ListItem>
</asp:ListBox>
</td>
</tr>
<!--Country and State Change Javascript-->
<script>
function countryChange() {
var countryState = [
[
'US', [
['', 'State/Province'],
['AL', 'Alabama'],
['AK', 'Alaska'],
['AZ', 'Arizona'],
['AR', 'Arkansas'],
], ],
[
'CA', [
['', 'State/Province'],
['AB', 'Alberta'],
['BC', 'British Columbia'],
['MB', 'Manitoba'],
['NB', 'New Brunswick'],
]]
];
var countryElement = document.getElementById('countryId');
var stateElement = document.getElementById('stateId');
var stateLabelElement = document.getElementById('stateLabel');
if (countryElement && stateElement) {
var listOfState = [
['XX', 'None']
];
var currentCountry = countryElement.options[countryElement.selectedIndex].value;
for (var i = 0; i < countryState.length; i++) {
if (currentCountry == countryState[i][0]) {
listOfState = countryState[i][1];
}
}
if (listOfstate.length < 2)
{
stateElement.style.display = 'none';
stateLabelElement.style.display = 'none';
}
else
{
stateElement.style.display = 'inline';
stateLabelElement.style.display = 'inline';
}
var selectedState;
for (var i = 0; i < stateElement.length; i++) {
if (stateElement.options[i].selected === true) {
selectedState = stateElement.options[i].value;
}
}
stateElement.options.length = 0;
for (var i = 0; i < listOfState.length; i++) {
stateElement.options[i] = new Option(listOfState[i][1], listOfState[i][0]);
if (listOfState[i][0] == selectedState) {
stateElement.options[i].selected = true;
}
}
}
}
</script>
Error I am getting:
Invalid postback or callback argument. Event validation is enabled
using in configuration or <%#
Page EnableEventValidation="true" %> in a page. For security
purposes, this feature verifies that arguments to postback or callback
events originate from the server control that originally rendered
them. If the data is valid and expected, use the
ClientScriptManager.RegisterForEventValidation method in order to
register the postback or callback data for validation.
I have several asp:checkboxes on my webform which are filled in on page load, then returned on button submit.
the buttons are always returning the same as the server boolean behind them, no matter whether changed on the client side before being returned. After checking the clientID of the variables, they are exactly the same so it is not down to any hidden IDs or anything like that.
ASPX
<script type="text/javascript">
function slideTable(link) {
$(link).parent().next().toggle()
$(link).find(".navPlus").toggleClass("rotate1");
$(link).find(".navPlus").toggleClass("rotate");
var txt = $(link).parent().next().is(':visible') ? 'Minimise' : 'View all';
$(link).find(".navPlus").text(txt);
};
function boxchange(box) {
//Change has already happened at this point
if ($(box).prop("checked")==true) {
$(box).attr("checked", "checked");
}
else {
$(box).removeAttr("checked");
}
var table = $(box).closest('table');
var allChecked = $('#subjectsTable :checkbox:checked').length == $('#subjectsTable :checkbox').length;
if (allChecked) {
$(table).prev().find(":input").prop("checked", true);
$(table).prev().find(":input").attr("checked", true);
}
else {
$(table).prev().find(":input").prop("checked", false);
$(table).prev().find(":input").attr("checked", false);
}
};
</script>
<div>
<span class="headerSpan" onclick="slideTable(this)" style="clear:both" >
<img class="logo-image" alt="HalsburyLogo" src="../images/siteStyle/logo.png"/>
<span class="navPlus rotate1">View all</span>
</span>
<input onclick="chkHeader_click(this)" style="float:none; display:inline" type="checkbox" id="chkSubjects"/>
</div>
<table id="subjectsTable" class="subscriptionTable">
<tr>
<td style="width: 300px">
<label>Art</label></td>
<td>
<asp:CheckBox onclick="boxchange(this)" ID="chkArt" CssClass="chkSubject" runat="server" /></td>
</tr>
</table>
When a submit button is clicked, the value of chkArt is always the same. - upon checking, the clientID of chkArt on the serverside is also chkArt
edit: in the page load event the following code is present:
chkArt.Checked = //a bool from the database
chkArt.Checked = //a bool from the database
This code is in Page_Load? Unless you're conditionally running this code (which you aren't in the question at least...) then this is being executed every time the page loads. Page_Load is invoked whenever a request is made to a page, postback or otherwise.
So essentially your page is receiving the changed values, but ignoring them and just resetting them to their previous state.
You can conditionally check for postbacks in Page_Load:
if (!IsPostBack)
chkArt.Checked = //a bool from the database
That way the initial state of the CheckBox is set only on the initial load of the page, and not re-set on every postback.
I want to implement feature in my TextBox where user will type some address and from Google API returns address from that user will select the correct address. And He will select the address my Street, Zip, Country, City all will automatically fill.
I am trying this but not get success ( Small part of my aspx page )
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true&libraries=places"></script>
<script type="text/javascript">
var placeSearch,autocomplete;
var component_form = {
'route': 'short_name',
'route': 'long_name',
'locality': 'long_name',
'administrative_area_level_1': 'short_name',
'country': 'long_name',
'postal_code': 'postal_code'
};
function initialize() {
autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete'), { types: [ 'geocode' ] });
google.maps.event.addListener(autocomplete, 'place_changed', function() {
fillInAddress();
});
}
function fillInAddress() {
var place = autocomplete.getPlace();
for (var component in component_form) {
document.getElementById(component).value = "";
document.getElementById(component).disabled = false;
}
for (var j = 0; j < place.address_components.length; j++) {
var att = place.address_components[j].types[0];
if (component_form[att]) {
var val = place.address_components[j][component_form[att]];
document.getElementById(att).value = val;
}
}
}
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
autocomplete.setBounds(new google.maps.LatLngBounds(geolocation, geolocation));
});
}
}
</script>
And my .aspx page is like this
<div onload="initialize();">
<asp:UpdatePanel ID="UpdatePanelTabContainer" runat="server">
<ContentTemplate>
<table width="100%">
<tr>
<td>
street
</td>
<td>
<asp:TextBox ID="txtPickupStreet" runat="server" MaxLength="100" Width="162px" placeholder="Enter your address" AutoPostBack="true" onFocus="javascript:geolocate()"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Postal Code
</td>
<td>
<asp:TextBox ID="txtPickupPC" runat="server" MaxLength="11" Width="90px" />
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
Here the user will type in street TextBox He will get relative result and select after that all TextBox will be fill .
Ok there are a few problems with your code.
I have made a working demo for you.
I did use jQuery for my additions, but I'm sure you can replace that if you aren't using jQuery.
component_form object is wrong
it should look like this
var component_form = {
'txtPickupUnitNumber': 'subpremise',
'txtPickupStreetNumber': 'street_number',
'txtPickupStreetName': 'route',
'txtPickupSuburb': 'locality',
'txtPickupPC': 'postal_code',
'txtPickupState': 'administrative_area_level_1',
'txtPickupCountry': 'country'
};
The array key is the id of the textbox and the value is the name of the google places result address_component type.
The geolocate function doesn't do anything useful
You are setting the autocomplete search bounds to one lat/lng coord. A bounds should be a collection of lat/lngs. If you are displaying a map on the same page as this form you could do as follows.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
// set the map to the user locations
map.setCenter(new google.maps.LatLng(position.coords.latitude,position.coords.longitude));
// use the viewport as the search bounds
autocomplete.setBounds(map.getBounds()));
});
}
}
The fillInAddress function will need to be changed to deal with the new component_form array.
function fillInAddress() {
var place = autocomplete.getPlace();
// if you use jQuery then you can delete this and just set the attr to true in the fillFormInput function
for (var component in component_form) {
document.getElementById(component).value = "";
document.getElementById(component).disabled = false;
}
for (var j = 0; j < place.address_components.length; j++) {
var att = place.address_components[j].types[0];
fillFormInput(att, place.address_components[j].long_name);
}
}
// This new function searchs for the textbox that corresponds to the address_component type name
function fillFormInput(att, val) {
for (var c in component_form) {
if (component_form[c] === att) {
$('#'+c).val(val);
}
}
}
I have one ASP.NET application which includes one gridview. This gridview contains 4 template columns of checkboxes and 2 template columns of link buttons. If I click on the first checkbox, then both of the link buttons should be enabled, otherwise they should be in disabled mode. This functionality is working fine. But my problem is, at the time of form loading, it will check whether the first column is checked or not. If the checkbox is not checked, the link buttons will be in disabled mode. But after the checking of this checkbox, it will enabled, but there is no link to redirect. My code is shown below.
protected void DGDocuments_ItemDataBound(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemIndex == -1) return;
BindCheckBox(e.Item, "chkRead");
BindCheckBox(e.Item, "chkCreate");
BindCheckBox(e.Item, "chkUpdate");
BindCheckBox(e.Item, "chkDelete");
CheckBox chkID = (CheckBox)e.Item.FindControl("chkRead");
if (!chkID.Checked)
{
LinkButton lnkPermission = (LinkButton)e.Item.FindControl("lnkFieldPermssion");
LinkButton lnkSetRules = (LinkButton)e.Item.FindControl("lnkAddRules");
lnkPermission.Enabled = false;
lnkSetRules.Enabled = false;
}
}
In designer page:
<asp:TemplateColumn HeaderText="Read" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkRead" runat="server" Text='<%# Eval("Read") %>' onclick="javascript:EnablePermissoin(this,5,6);" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Rules" ItemStyle-HorizontalAlign="Center" ItemStyle-Font-Bold="true">
<ItemTemplate>
<asp:LinkButton ID="lnkAddRules" Text="Add Rules" runat="server" CommandName="cmdSetRules" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Field Permission" ItemStyle-HorizontalAlign="Center" ItemStyle-Font-Bold="true">
<ItemTemplate>
<asp:LinkButton ID="lnkFieldPermssion" Text="Set" runat="server" CommandName="cmdFieldPermission" />
</ItemTemplate>
</asp:TemplateColumn>
Javascript is:
function EnablePermissoin(chkB, cellNumber1, cellNumber2) {
var IsChecked = chkB.checked;
if (IsChecked) {
var cell1 = chkB.parentElement.parentElement.cells[cellNumber1];
for (i = 0; i < cell1.childNodes.length; i++) {
if (cell1.childNodes[i].tagName == "A") {
cell1.childNodes[i].disabled = false;
}
}
var cell2 = chkB.parentElement.parentElement.cells[cellNumber2];
for (i = 0; i < cell2.childNodes.length; i++) {
if (cell2.childNodes[i].tagName == "A") {
cell2.childNodes[i].disabled = false;
}
}
}
else {
var cell1 = chkB.parentElement.parentElement.cells[cellNumber1];
for (i = 0; i < cell1.childNodes.length; i++) {
if (cell1.childNodes[i].tagName == "A") {
cell1.childNodes[i].disabled = true;
}
}
var cell2 = chkB.parentElement.parentElement.cells[cellNumber2];
for (i = 0; i < cell2.childNodes.length; i++) {
if (cell2.childNodes[i].tagName == "A") {
cell2.childNodes[i].disabled = true;
}
}
}
}
This is the code obtained from view source of the browser, without disabling the link button on form loading:
<td align="center" style="font-weight:bold;">
<a id="DGDocuments_ctl23_lnkAddRules" href="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("DGDocuments$ctl23$lnkAddRules", "", true, "", "", false, true))">Add Rules</a>
</td><td align="center" style="font-weight:bold;">
<a id="DGDocuments_ctl23_lnkFieldPermssion" href="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("DGDocuments$ctl23$lnkFieldPermssion", "", true, "", "", false, true))">Set</a>
</td>
If I disable the link button on loading, this will be the code obtained from the view source:
<td align="center" style="font-weight:bold;">
<a id="DGDocuments_ctl23_lnkAddRules" disabled="disabled">Add Rules</a>
</td><td align="center" style="font-weight:bold;">
<a id="DGDocuments_ctl23_lnkFieldPermssion" disabled="disabled">Set</a>
</td>
Please help me to solve this. Thanks in advance.
It looks like when you disable the LinkButton server-side, it doesn't generate the onclick event handler for the a tag. So, once you enable the LinkButton through JavaScript, it doesn't know how to post back. I would suggest either rendering the LinkButton normally and then disabling it through JavaScript or setting AutoPostback to True for the checkbox and do the enabling server-side.
You are going to have to reconsider your solution. LinkButtons simply generate an <A> tag in the HTML. An <A> tag cannot be "disabled", so when you set a LinkButton to be Disabled, ASP.NET removes the HREF from the tag so that clicking it does nothing. I should point out that your JavaScript for disabling the <A> tag does not work - it makes the <A> tag look disabled, but it is still clickable.
For this to work client side, you will need your JavaScript function to add and remove the HREF from the <A> tag. Other options include doing everything server side, so that ASP.NET handles the removal and addition of the HREF, or switching to a different control, such as a regular asp:Button, which can be enabled and disabled.