Calling a javascript select change from c# - asp.net

I have javascript function when a control value is changed i am firing a javascript now i wanted to do from c# code.When a value to a control is assigned i wanted it to fire the javascript .Please Help !!.
function AddSelectedUser(sender, eventArgs) {
var dataItem = eventArgs.get_DataItem();
if (dataItem != null) {
// get the selected values
var subscribedUserId = parseInt(eventArgs.get_Value());
var subscribedUserText = eventArgs.get_Text();
var recipientType = dataItem.get_attributes().getAttribute("RecipientType");
//Check if the selected user or group already exists in the selected list
var isExisting = false;
var JSONString = $get(hdnSelectedUsersJsonId).value;
var selectedUserColl = new Array();
if (JSONString != "") {
selectedUserColl = Sys.Serialization.JavaScriptSerializer.deserialize(JSONString);
}
for (j = 0; j < selectedUserColl.length; j++) {
if (selectedUserColl[j].DisplayID == subscribedUserId && selectedUserColl[j].RecipientType == recipientType) {
isExisting = true;
break;
}
}
if (isExisting == false) {
//Add the selected user or group.
var emptyRecipient = new Object();
emptyRecipient.DisplayID = subscribedUserId;
emptyRecipient.DisplayName = subscribedUserText;
emptyRecipient.RecipientType = recipientType;
selectedUserColl.push(emptyRecipient);
$get(hdnSelectedUsersJsonId).value = Sys.Serialization.JavaScriptSerializer.serialize(selectedUserColl);
ConstructTable(false);
}
sender.resetData();
var divScroll = $get('selectedUsersDiv');
divScroll.scrollTop = divScroll.scrollHeight;
}
}
<tele:autocomplete runat="server" pickervisible="false" id="SubscribedUsers" height="100px"
width="250px" dropdownwidth="248px" cssclass="susbscribedUser" pickertooltip="Select Users or Notification Groups"
providertype="InstantNotificationUsersProvider" matchingtype="Contains" controlbehavior="RestrictedToDropdown"
onclientsidecomponentchanged="AddSelectedUser" AutoPostBack="true" />

If you just want to call this function from c# then use ScriptManager.RegisterStartupScript() method.
It's easy just read this method properly and call you function.

Related

Using multi filter datatables in asp.net MVC

I'm trying to implement the multiple filters in the datatables in asp.net, but the time I search a value, my table is not updated.
I followed the official example of the site, but it did not work. Here is the source code I'm using.
JS on VIEW
$('#students tfoot th').each( function () {
var title = $(this).text();
if (title !== "") {
$(this).html('<input type="text" class="form-control form-control-sm" style="width: 100%" placeholder="' + title + '" />');
} else {
$(this).html('<div class="text-center">-</div>');
}
} );
tabela.columns().every( function () {
var that = this;
$( 'input', this.header() ).on( 'keydown', function (ev) {
if (ev.keyCode == 13) { //only on enter keypress (code 13)
that
.search( this.value )
.draw();
}
} );
} );
ACTION on CONTROLLER
[HttpPost]
public JsonResult Listar2()
{
var search = Request.Form.GetValues("search[value]")?[0];
var list = db.Students;
if (!string.IsNullOrEmpty(search))
{
list = list.Where(m => m.name.ToLower().Contains(search.ToLower()) || m.class.ToLower().Contains(search.ToLower()));
}
var draw = Request.Form.GetValues("draw")?[0];
var start = Request.Form.GetValues("start")?[0];
var length = Request.Form.GetValues("length")?[0];
var width = length != null ? Convert.ToInt32(length) : 0;
var skip = start != null ? Convert.ToInt32(start) : 0;
var totalRecords = list.Count();
var resultFinal = list.Skip(skip).Take(width).ToList();
return Json(new
{
data = resultFinal,
draw,
recordsFiltered = totalRecords,
recordsTotal = totalRecords
});
}
I don't know what you want to accomplish. The official example uses JavaScript to sort the datatable which is inserted into HTML already. You should load all the entries first, pass them to the view and then this script should filter those entries

Validation with ajax AutoCompleteExtender

I have a TextBox with AutoCompleteExtenderwhen the person starts typing in the TextBox List with City name Appear .This works fine but now I want to validate that if they just type in a textbox and don't select one from the list that it validates that City Is Not Exist In database.
I want to validate it Using Ajax And Without PostBack Before Final Submit of form.
Add new js file with content below and add add reference on it to ToolkitScriptManager's Scrips collection:
Type.registerNamespace('Sjax');
Sjax.XMLHttpSyncExecutor = function () {
Sjax.XMLHttpSyncExecutor.initializeBase(this);
this._started = false;
this._responseAvailable = false;
this._onReceiveHandler = null;
this._xmlHttpRequest = null;
this.get_aborted = function () {
//Parameter validation code removed here...
return false;
}
this.get_responseAvailable = function () {
//Parameter validation code removed here...
return this._responseAvailable;
}
this.get_responseData = function () {
//Parameter validation code removed here...
return this._xmlHttpRequest.responseText;
}
this.get_started = function () {
//Parameter validation code removed here...
return this._started;
}
this.get_statusCode = function () {
//Parameter validation code removed here...
return this._xmlHttpRequest.status;
}
this.get_statusText = function () {
//Parameter validation code removed here...
return this._xmlHttpRequest.statusText;
}
this.get_xml = function () {
//Code removed
}
this.executeRequest = function () {
//Parameter validation code removed here...
var webRequest = this.get_webRequest();
if (webRequest === null) {
throw Error.invalidOperation(Sys.Res.nullWebRequest);
}
var body = webRequest.get_body();
var headers = webRequest.get_headers();
var verb = webRequest.get_httpVerb();
var xmlHttpRequest = new XMLHttpRequest();
this._onReceiveHandler = Function.createCallback(this._onReadyStateChange, { sender: this });
this._started = true;
xmlHttpRequest.onreadystatechange = this._onReceiveHandler;
xmlHttpRequest.open(verb, webRequest.getResolvedUrl(), false); // False to call Synchronously
if (headers) {
for (var header in headers) {
var val = headers[header];
if (typeof (val) !== "function") {
xmlHttpRequest.setRequestHeader(header, val);
}
}
}
if (verb.toLowerCase() === "post") {
if ((headers === null) || !headers['Content-Type']) {
xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
if (!body) {
body = '';
}
}
this._started = true;
this._xmlHttpRequest = xmlHttpRequest;
xmlHttpRequest.send(body);
}
this.getAllResponseHeaders = function () {
//Parameter validation code removed here...
return this._xmlHttpRequest.getAllResponseHeaders();
}
this.getResponseHeader = function (header) {
//Parameter validation code removed here...
return this._xmlHttpRequest.getResponseHeader(header);
}
this._onReadyStateChange = function (e, args) {
var executor = args.sender;
if (executor._xmlHttpRequest && executor._xmlHttpRequest.readyState === 4) {
//Validation code removed here...
executor._responseAvailable = true;
executor._xmlHttpRequest.onreadystatechange = Function.emptyMethod;
executor._onReceiveHandler = null;
executor._started = false;
var webRequest = executor.get_webRequest();
webRequest.completed(Sys.EventArgs.Empty);
//Once the completed callback handler has processed the data it needs from the XML HTTP request we can clean up
executor._xmlHttpRequest = null;
}
}
}
Sjax.XMLHttpSyncExecutor.registerClass('Sjax.XMLHttpSyncExecutor', Sys.Net.WebRequestExecutor);
On a page:
<ajaxToolkit:ToolkitScriptManager runat="server" ID="ScriptManager1">
<Scripts>
<asp:ScriptReference Path="~/XMLHttpSyncExecutor.js" />
</Scripts>
</ajaxToolkit:ToolkitScriptManager>
Then, add CustomValidator for target TextBox and use function below for client validation:
<asp:TextBox runat="server" ID="myTextBox" Width="300" autocomplete="off" />
<asp:CustomValidator runat="server" ID="myTbCustomValidator" ControlToValidate="myTextBox"
Text="*" Display="Dynamic" ValidateEmptyText="false" ClientValidationFunction="validateTextBox"
OnServerValidate="ValidateTextBox" />
function validateTextBox(sender, args) {
if (args.Value.length > 0) {
var extender = $find("AutoCompleteEx"); // AutoComplete extender's BehaviorID
if (extender._completionListElement) {
var children = extender._completionListElement.childNodes;
var length = extender._completionListElement.childNodes.length;
for (var i = 0; i < length; i++) {
if (children[i].innerHTML == args.Value) {
args.IsValid = true;
return;
}
}
}
var request = new Sys.Net.WebRequest();
request.set_url('<%= ResolveClientUrl("~/AutoComplete/AutoComplete.asmx/Validate") %>');
var body = Sys.Serialization.JavaScriptSerializer.serialize({ value: args.Value });
request.set_body(body);
request.set_httpVerb("POST");
request.get_headers()["Content-Type"] = "application/json; encoding=utf-8";
request.add_completed(function (eventArgs) {
var result = Sys.Serialization.JavaScriptSerializer.deserialize(eventArgs.get_responseData());
args.IsValid = result.d;
});
var executor = new Sjax.XMLHttpSyncExecutor();
request.set_executor(executor);
request.invoke();
}
}
The main idea of code above is to check suggested items at first for entered text and if there aren't any concidence then to do synchronous AJAX call to Validate method of web service or page method. That method should have such signature: public bool Validate(string value)
P.S. Code for XMLHttpSyncExecutor taken here: Using Synchronous ASP.Net AJAX Web Service Calls and Scriptaculous to Test your JavaScript

Page Got Postback in OnClientClick Return False

I am working in C#.Net. i am having an asp button..
<asp:Button ID="btnSubmitData" ToolTip="Show" runat="server" Text="SHOW" CausesValidation="false"
OnClientClick="return FindSelectedItems();" OnClick="btnShow_Click" />
The function called in OnClientClick is,
function FindSelectedItems() {
var sender = document.getElementById('lstMultipleValues');
var cblstTable = document.getElementById(sender.id);
var checkBoxPrefix = sender.id + "_";
var noOfOptions = cblstTable.rows.length;
var selectedText = "";
var total = 0;
for (i = 0; i < noOfOptions; ++i) {
if (document.getElementById(checkBoxPrefix + i).checked) {
total += 1;
if (selectedText == "")
selectedText = document.getElementById
(checkBoxPrefix + i).parentNode.innerText;
else
selectedText = selectedText + "," +
document.getElementById(checkBoxPrefix + i).parentNode.innerText;
}
}
var hifMet1 = document.getElementById('<%=hifMet1.ClientID%>');
hifMet1.value = selectedText;
if (total == 0) {
var panel = document.getElementById('<%=pnlOk.ClientID%>');
document.getElementById('<%=pnlOk.ClientID%>').style.display = 'block';
var Label1 = document.getElementById('<%=Label3.ClientID%>');
Label1.innerHTML = "Atleast one metric should be selected.";
var btnLoc = document.getElementById('<%=btnLoc.ClientID%>');
btnLoc.disabled = true;
var btnProd = document.getElementById('<%=btnProd.ClientID%>');
btnProd.disabled = true;
var btnLastYear = document.getElementById('<%=btnLastYear.ClientID%>');
btnLastYear.disabled = true;
return false;
}
else if (total > 2) {
var panel = document.getElementById('<%=pnlOk.ClientID%>');
document.getElementById('<%=pnlOk.ClientID%>').style.display = 'block';
var Label1 = document.getElementById('<%=Label3.ClientID%>');
Label1.innerHTML = "Only two metrics can be compared.";
var btnLoc = document.getElementById('<%=btnLoc.ClientID%>');
btnLoc.disabled = true;
var btnProd = document.getElementById('<%=btnProd.ClientID%>');
btnProd.disabled = true;
var btnLastYear = document.getElementById('<%=btnLastYear.ClientID%>');
btnLastYear.disabled = true;
return false;
}
else {
return true;
}
}
Once i click the SHOW Button, i need to do a validation to check at least one checkbox should get checked in checkbox list. That alert message i am getting (i.e) "Atleast one metric should be selected". But after this part, the page gets reloaded.
I want to avoid the page refresh at this point. What should i do here.?
One way is to hook your validation function into the proper ASP .Net validation lifecycle by using a CustomValidator control and a client validation function.
With a few minor changes you can turn your JavaScript code into a client validation function.
Full example here.
Relevant Snippets
<script language="javascript">
function ClientValidate(source, arguments)
{
// Your code would go here, and set the IsValid property of arguments instead
// of returning true/false
if (arguments.Value % 2 == 0 ){
arguments.IsValid = true;
} else {
arguments.IsValid = false;
}
}
</script>
<asp:CustomValidator id="CustomValidator1"
ControlToValidate="Text1"
ClientValidationFunction="ClientValidate"
OnServerValidate="ServerValidation"
Display="Static"
ErrorMessage="Not an even number!"
ForeColor="green"
Font-Name="verdana"
Font-Size="10pt"
runat="server"/>
<asp:Button id="Button1"
Text="Validate"
OnClick="ValidateBtn_OnClick"
runat="server"/>
Client validation should always be double-checked with server validation; using a CustomValidator with both client/server validation functions is a good way to accomplish this.
Remove script
else {
return true;
}
part from script and call function like this
OnClientClick="javascript:return FindSelectedItems();"
This work for me.

accessing checkboxlist text through javascript

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;
}

runtime generated Checkbox validation

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;
}

Resources