As going through the site i got how to access the model in javascript and how to loop it in javascript.
i am using text tag to access the item in a model. when i use i am not able to add break.
#foreach (var item in Model.ArrayDetails)
{
var checklower = false;
var checkUpper = false;
var loopentered = false;
<text>
if(#item.Id ==1)
{
if(#item.LowerBound <= obj.value)
{
loopentered=true;
checklower=true;
}
if(loopentered)
{
alert(#item.UpperBound <= obj.value);
if(#item.UpperBound <= obj.value)
{
checkUpper = true;
}
}
if(checkUpper && checklower)
{
***// here i want to add break statement(if i add javascript wont work)***
}
}
</text>
}
Can some one suggest me how can solve this.
Don't write this soup. JSON serialize your model into a javascript variable and use this javascript variable to write your javascript code. Right now you have a terrible mixture of server side and client side code.
Here's what I mean in practice:
<script type="text/javascript">
// Here we serialize the Model.ArrayDetails into a javascript array
var items = #Html.Raw(Json.Encode(Model.ArrayDetails));
// This here is PURE javascript, it could (AND IT SHOULD) go into
// a separate javascript file containing this logic to which you could
// simply pass the items variable
for (var i = 0; i < items.length; i++) {
var item = items[i];
var checklower = false;
var checkUpper = false;
var loopentered = false;
if (item.Id == 1) {
if (item.LowerBound <= obj.value) {
loopentered = true;
checklower = true;
}
if (loopentered) {
alert(item.UpperBound <= obj.value);
if(item.UpperBound <= obj.value) {
checkUpper = true;
}
}
if (checkUpper && checklower) {
break;
}
}
}
</script>
and after moving the javascript into a separate file your view will simply become:
<script type="text/javascript">
// Here we serialize the Model.ArrayDetails into a javascript array
var items = #Html.Raw(Json.Encode(Model.ArrayDetails));
myFunctionDefinedIntoASeparateJavaScriptFile(items);
</script>
Related
I have a checkbox list i have which i have bound some document name to it's text field.now i need to find only the checkboxes which the text contains the .pdf extension and check them all in a single checkbox click.i have written the following javascript but it doesn't work for me
function CheckAllPDF() {
var checkBoxList = document.getElementById("<%= cblFiles.ClientID %>");
var checkBoxes = checkBoxList.getElementsByTagName("input");
for (i = 0; i < checkBoxes.length; i++) {
var string = checkBoxes[i].parentNode.getElementsByTagName('label').innerHTML;
var match = string.indexOf(".pdf");
if (match != -1) {
checkBoxes[i].checked = true;
}
else {
checkBoxes[i].checked = false;
}
}
can some one help?
When you put an asp.net check box list in the page it is translated to a list of input of type checkbox so you need to access each control and check it so you javascript code should look like:
//Get the main id of the asp.net check box list
var checkboxId = '<%= CheckBoxList1.ClientID %>';
//Loop on all generated input check boxes where the count function determine the number of generated checkboxes
for (var i = 0; i < <%= Count() %>; i++) {
//Append the count on the main asp.net check box id the value ('_'+i)
var checkBox = document.getElementById(checkboxId + '_' + i);
var checkBoxValue = checkBox.value;
var match = checkBoxValue.indexOf(".pdf");
if (match != -1) {
checkBox.checked = true;
}
else {
checkBox.checked = false;
}
}
And in your code behind write the count function as follows:
public int Count()
{
return CheckBoxList1.Items.Count;
}
I have panel in the asp.net webpage, and i m generating the checkbox at runtime..
i want to validate checkbox, required field validator when form submit.
here is my code:
cv = new CustomValidator();
cv.ID = "cv" + "_" + dt.Rows[0]["RefQueID"].ToString();
cv.ValidationGroup = "grp";
cv.Display = ValidatorDisplay.None;
cv.ErrorMessage = "- Question " + intQuestionNo.ToString();
cv.ClientValidationFunction = "chkCount";
cv.Attributes.Add("rfvid", cv.ID.ToString());
//this portion of code is for custom validation javascript function
StringBuilder sb = new StringBuilder();
sb.Append("<script type='text/javascript'> function chkCount(sender,args) { ");
sb.Append(" args.IsValid = GetChk(document.getElementById('ctl00_ContentPlaceHolder1_" + cbl.ID.ToString() + "'))");
sb.Append(" } </script>");
Page page = HttpContext.Current.Handler as Page;
page.RegisterStartupScript("_Check", sb.ToString());
and in my javascript function i return this:
function GetChk(chkbox, args) {
if (!isConfirmed) {
alert('hi');
var chkBoxList = document.getElementById(chkbox.ClientID);
var chkBoxCount = chkBoxList.getElementsByTagName("input");
for (var i = 0; i < chkBoxCount.length; i++) {
if (chkBoxCount[i].checked == true) {
return true;
}
}
return false;
}
return true;
}
but i m not getting the value of the checkbox...
required value:=
ctl00_ContentPlaceHolder1_tc_hospital_improvement_features_tp_Reflection_cbl_116_0
Actual Value:=
ctl00_ContentPlaceHolder1_tc_hospital_improvement_features_tp_complete_stage_chk_confirm
pls help...
first get the runtime generated control into the codebehind file from class file.
and then secondly after getting the control property, we can validate the checbox list.
Get the control into codebehind file from class file.
CheckBoxList cbl = (CheckBoxList)pnlref.FindControl("cbl_116");
provide the javascript validation to the runtime generated checkbox list.
function GetChk(chkbox, args) {
if (!isConfirmed) {
var chkBoxList = document.getElementById('ctl00_ContentPlaceHolder1_tc_hospital_improvement_features_tp_Reflection_cbl_116');
var chkBoxCount = chkBoxList.getElementsByTagName("input");
for (var i = 0; i < chkBoxCount.length; i++) {
if (chkBoxCount[i].checked == true) {
return true;
}
}
return false;
}
return true;
}
How do I reset an asp.net validation control via JavaScript? The current code sample clears the error message text but does not reset the validation control for the next form submission.
var cv= document.getElementById("<%= MyValidationContorl.ClientID %>");
cv.innerHTML = '';
Update:
Here is the full code sample of the form. I can not seem to get the validation controls fire off on another form submission:
function ClearData() {
var cv = document.getElementById("<%= MyValidationContorl.ClientID %>");
cv.innerHTML = '';
}
<html>
<form>
<asp:TextBox id="MyTextControl" runat="server" />
<asp:CustomValidator ID="MyValidationContorl" runat="server" />
<input type="button" onclick="javascript:ClearCCData(); return false;" runat="server" />
</form>
</html>
Page validation is fired every time you do a post, what appears to be the problem is that you are clearing the validator content cv.innerHTML = '';, this way your validator message is lost forever and you'll think validation is not firing again.
and for #Glennular answer, the code does not handle the validator Display property, if its set to Dynamic the validator will be toggled using validator.style.display, but if its set to None or Inline then validator.style.visibility property will be used instead.
Its better to use asp.net ValidatorUpdateDisplay instead,
<script type="text/javascript">
function Page_ClientValidateReset() {
if (typeof (Page_Validators) != "undefined") {
for (var i = 0; i < Page_Validators.length; i++) {
var validator = Page_Validators[i];
validator.isvalid = true;
ValidatorUpdateDisplay(validator);
}
}
}
</script>
Update : Reset Validation Summaries
<script type="text/javascript">
function Page_ValidationSummariesReset(){
if (typeof(Page_ValidationSummaries) == "undefined")
return;
for (var i = 0; i < Page_ValidationSummaries.length; i++)
Page_ValidationSummaries[i].style.display = "none";
}
</script>
This one resets all validators in all validation groups.
<script type="text/javascript">
Page_ClientValidate('');
</script>
Try the following chunk of code :
$("#<%= txtUserSettingsEmailRequiredValidator.ClientID %>").css("display", "none");
I hope this will work as it worked for me. :)
Here's code to reset all validators
function CleanForm() {
document.forms[0].reset();
for (i = 0; i < Page_Validators.length; i++) {
Page_Validators[i].style.visibility = 'hidden';
}
return false;
}
or a single one:
document.getElementById("<%= MyValidationContorl.ClientID %>").style.visibility
= 'hidden';
Using the Page_Validators[i].style.visibility = 'hidden';
Don't work for me so I use this line of code instead: Page_Validators[i].enabled = false;
if (sFirstName == "" && sLastName == "")
{
alert('Reminder: Please first enter student ID to search for the student information before filling out the rest of the form field values');
//Disable all require field validation coontrol on the form so the user could continue to use the Lookup student function.
document.forms[0].reset();
for (i = 0; i < Page_Validators.length; i++) {
//Page_Validators[i].style.visibility = 'hidden';
Page_Validators[i].enabled = false;
}
return false;
}
else
{
alert('Student Name = ' + sFirstName + ' ' + sLastName);
document.forms[0].reset();
for (i = 0; i < Page_Validators.length; i++) {
//Page_Validators[i].style.visibility = 'hidden';
Page_Validators[i].enabled = true;
}
return true;
}
im using javascript like
var TargetBaseControl = null;
window.onload = function()
{
try
{
//get target base control.
TargetBaseControl =
document.getElementById('<%= this.GridView1.ClientID %>');
}
catch(err)
{
TargetBaseControl = null;
}
}
function TestCheckBox()
{
if(TargetBaseControl == null) return false;
//get target child control.
var TargetChildControl = "chkSelect";
//get all the control of the type INPUT in the base control.
var Inputs = TargetBaseControl.getElementsByTagName("input");
for(var n = 0; n < Inputs.length; ++n)
if(Inputs[n].type == 'checkbox' &&
Inputs[n].id.indexOf(TargetChildControl,0) >= 0 &&
Inputs[n].checked)
return true;
alert('Select at least one checkbox!');
return false;
}
and inside the update panel i have code like
<asp:Button ID="ButtonSave" runat="server" OnClick="ButtonSave_Click"
OnClientClick="javascript:return TestCheckBox();" Text="Save" />
when i run the page and click the button then no more further processing just button has been click nothing happan......
Try this:
function TestCheckBox()
{
var TargetBaseControl = null;
if(TargetBaseControl = document.getElementById('<%= this.GridView1.ClientID %>')){
//get target child control.
var TargetChildControl = "chkSelect";
//get all the control of the type INPUT in the base control.
var Inputs = TargetBaseControl.getElementsByTagName("input");
for(var n = 0; n < Inputs.length; ++n)
if(Inputs[n].type == 'checkbox' &&
Inputs[n].id.indexOf(TargetChildControl,0) >= 0 &&
Inputs[n].checked)
return true;
}
alert('Select at least one checkbox!');
return false;
}
look at the source of your page once it is in a browser.
see what happens with the OnClientClick assignment.
does it get rewritten/re-routed ?
it should be pretty clear at that point.
you can also step through with tools such as Firebug in firefox, IE8 developer tools, chrome developer tools, or visual studio
I have form in ASP.NET 3.5. Where lot of data elements and where i have Save and Submit buttions. I need to auto save my form every 2 min. What is the best way to implement this kind of functionility in ASP.NET.
I struggled for awhile with the same problem. The trouble was that I didn't want to save into the usual database tables because that would've required validation (validating integers, currencies, dates, etc). And I didn't want to nag the user about that when they may be trying to leave.
What I finally came up with was a table called AjaxSavedData and making Ajax calls to populate it. AjaxSavedData is a permanent table in the database, but the data it contains tends to be temporary. In other words, it'll store the user's data temporarily until they actually complete the page and move onto the next one.
The table is composed of just a few columns:
AjaxSavedDataID - int:
Primary key.
UserID - int:
Identify the user (easy enough).
PageName - varchar(100):
Necessary if you're working with multiple pages.
ControlID - varchar(100):
I call this a ControlID, but it's really just the ClientID property that .NET exposes for all of the WebControls. So if for example txtEmail was inside a user control named Contact then the ClientID would be Contact_txtEmail.
Value - varchar(MAX):
The value the user entered for a given field or control.
DateChanged - datetime:
The date the value was added or modified.
Along with some custom controls, this system makes it easy for all of this to "just work." On our site, the ClientID of each textbox, dropdownlist, radiobuttonlist, etc is guaranteed to be unique and consistent for a given page. So I was able to write all of this so that the retrieval of the saved data works automatically. In other words, I don't have to wire-up this functionality every time I add some fields to a form.
This auto-saving functionality will be making its way into a very dynamic online business insurance application at techinsurance.com to make it a little more user friendly.
In case you're interested, here's the Javascript that allows auto-saving:
function getNewHTTPObject() {
var xmlhttp;
/** Special IE only code */
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end
#*/
/** Every other browser on the planet */
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
}
catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
function AjaxSend(url, myfunction) {
var xmlHttp = getNewHTTPObject();
url = url + "&_did=" + Date();
xmlHttp.open("GET", url, true);
var requestTimer = setTimeout(function() { xmlHttp.abort(); }, 2000);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2005 00:00:00 GMT");
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState != 4)
return;
var result = xmlHttp.responseText;
myfunction(result);
};
xmlHttp.send(null);
}
// Autosave functions
var SaveQueue = []; // contains id's to the DOM object where the value can be found
var SaveQueueID = []; // contains id's for binding references (not always the same)
function ArrayContains(arr, value) {
for (i = 0; i < arr.length; i++) {
if (arr[i] == value)
return true;
}
return false;
}
function GetShortTime() {
var a_p = "";
var d = new Date();
var curr_hour = d.getHours();
if (curr_hour < 12)
a_p = "AM";
else
a_p = "PM";
if (curr_hour == 0)
curr_hour = 12;
else if (curr_hour > 12)
curr_hour = curr_hour - 12;
var curr_min = d.getMinutes();
curr_min = curr_min + "";
if (curr_min.length == 1)
curr_min = "0" + curr_min;
return curr_hour + ":" + curr_min + " " + a_p;
}
function Saved(result) {
if (result == "OK") {
document.getElementById("divAutoSaved").innerHTML = "Application auto-saved at " + GetShortTime();
document.getElementById("divAutoSaved").style.display = "";
}
else {
document.getElementById("divAutoSaved").innerHTML = result;
document.getElementById("divAutoSaved").style.display = "";
}
}
function getQueryString(name, defaultValue) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == name) {
return pair[1];
}
}
return defaultValue;
}
function urlencode(str) {
return escape(str).replace(/\+/g, '%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/#/g, '%40');
}
function AutoSave() {
if (SaveQueue.length > 0) {
var url = "/AjaxAutoSave.aspx?step=" + getQueryString("step", "ContactInformation");
for (i = 0; i < SaveQueue.length; i++) {
switch (document.getElementById(SaveQueue[i]).type) {
case "radio":
if (document.getElementById(SaveQueue[i]).checked)
url += "&" + SaveQueueID[i] + "=" + urlencode(document.getElementById(SaveQueue[i]).value);
break;
case "checkbox":
if (document.getElementById(SaveQueue[i]).checked)
url += "&" + SaveQueueID[i] + "=" + urlencode(document.getElementById(SaveQueue[i]).value);
default:
url += "&" + SaveQueueID[i] + "=" + urlencode(document.getElementById(SaveQueue[i]).value);
}
}
SaveQueue = [];
SaveQueueID = [];
AjaxSend(url, Saved);
}
}
function AddToQueue(elem, id) {
if (id == null || id.length == 0)
id = elem.id;
if (!ArrayContains(SaveQueueID, id)) {
SaveQueue[SaveQueue.length] = elem.id;
SaveQueueID[SaveQueueID.length] = id;
}
}
Add this to your page to make this work:
window.setInterval("AutoSave()", 5000);
And to apply this to a Textbox, DropdownList, Listbox, or Checkbox you just need to add this attribute:
onchange="AddToQueue(this)"
...or this for a RadioButtonList or CheckBoxList:
onchange="AddToQueue(this, '" + this.ClientID + "')"
I'm sure this Javascript could be simplified quite a bit if you used JQuery so you might want to consider that. But in any case, AJAX is the thing to use. It's what Google uses to auto-save your email message in gmail, and the same thing is in blogger when you're writing a new post. So I took that concept and applied it to a huge ASP.NET application with hundreds of form elements and it all works beautifully.
Use the Timer class and the Tick method.