I understand how to use jQuery to make an AJAX call to a WebMethod from a normal page, but I'm running into problems doing it from a UserControl (ASCX). Right now the biggest Issue I'm having is that the JavaScript for getting access to the groupDropDown control is not working. It seems that since this is a UserControl hosted within DotNetNuke, the ususal method of getting the CLientID is not working since it is nested down x number of levels. Here is what I have:
Javascript:
function validateEnrolledDate(src, args) {
var isValid;
var groupDropDown = document.getElementById('<%= ddlDealer.ClientID %>');
$.ajax({
type: "POST",
url: "ajaxservice.asmx/ValidateEnrolledDate",
data: "{orderDate: '" + args.Value + "', groupId: '" + groupId + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (msg) {
alert(msg);
isValid = msg.d;
},
failure: function () {
alert("FAIL");
}
});
args.IsValid = isValid;
Validator User Control that calls this JavaScript:
<asp:CustomValidator id="CustomValidator1" runat="server" ControlToValidate="rdiDate" ErrorMessage="Fail" OnServerValidate="CustomValidator1_ServerValidate" ValidationGroup="vgce" CssClass="validation" Display="Dynamic" Text="*" ClientValidationFunction="validateEnrolledDate" />
groupDropDown I'm trying to get a value from:
<asp:DropDownList ID="ddlDealer" runat="server" CssClass="dropdownlist theDealer" TabIndex="3" AutoPostBack="true" OnSelectedIndexChanged="ddlDealers_Changed" />
WebMethod:
[WebMethod()]
private bool ValidateEnrolledDate(string orderDate, string groupId)
{
DateTime enrolledDate = new Service().GetEnrollmentDate(int.Parse(groupId));
if (DateTime.Parse(orderDate) >= enrolledDate)
{
return true;
}
else
{
return false;
}
}
TIME TO SIMPLIFY:
Here is testing JS Code:
function validateEnrolledDate(src, args) {
var isValid;
var selectedGroup = $("theDealer").val();
alert(selectedGroup);
}
I'm now just referencing a TextBox:
<asp:TextBox ID="dealerId" runat="server" CssClass="theDealer" />
The Text in the Textbox is being set in Server Side code, and it is visible on screen.
The alert message is "undefined", so something is still happening so that it is not getting the value of that textbox...
If you are having trouble getting the value of the drop down list the easist approach would be to assign a class to the control.
<asp:DropDownList ID="ddlUsers" runat="server" CssClass="dropdownlist theUsers" TabIndex="5" AutoPostBack="true" OnSelectedIndexChanged="ddlUsers_SelectedIndexChanged" Enabled="false" />
and than in your method.
var selectedUser = $("theUsers option:selected").val();
Related
I am working with .Net Framework 4.6.1 I have a aspx page that renders data using a Telerik controller. I need to be able to pass properties from the Telerik controller back to the C# page. I have it set up so that when the user clicks on a row column it runs the ajax method with a hardcoded value. I'm unable to send my value using Ajax, I get sent to the error response right away. Is there something I'm doing wrong? I'm searched everywhere for documentation but none of it works with my framework...
aspx.cs page
aspx page
ASPX Page
<telerik:RadGrid ID="RadGrid1" runat="server" AllowPaging="False" AllowSorting="False" AllowFilteringByColumn="False" OnNeedDataSource="GetPharmacyByCorporate">
<ClientSettings>
<Scrolling AllowScroll="True" ScrollHeight="650px" UseStaticHeaders="True"></Scrolling>
<ClientEvents OnRowClick="sendIndex" />
<%-- On user click (client side) --%>
</ClientSettings>
<MasterTableView>
<Columns>
</Columns>
<%-- Columns renders every item passed --%>
</MasterTableView>
</telerik:RadGrid>
<script>
function sendIndex() {
$.ajax({
url: "/CorpPharmacyList/getIndexed",
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: { "indexValue": "4" },
success: function (data) {
if (data) {
console.log("Post successful");
}
},
error: function (e) {
console.log("There was an error with the ajax call")
}
})
}
</script>
C# Page
public class indexed
{
public int indexValue { get; set; }
}
[WebMethod]
public void getIndexed(indexed indexe)
{
try {
var myVar = indexe.indexValue;
}
catch (Exception ex)
{
}
}
Based on a comment on the question above...
This is the error I'm gettng "Unexpected token '<', " <!DOCTYPE "... is not valid JSON"
That means the server isn't returning JSON, it's returning HTML. But the JavaScript code is explicitly expecting JSON:
dataType: 'json',
Looking at the server-side code, this makes sense. Because the server-side code doesn't return anything:
public void getIndexed(indexed indexe)
So it would appear that it is defaulting to a page of some kind.
You can tell the JavaScript code to expect HTML instead:
dataType: 'html',
If you modify the server-side code to return JSON data, just remember to change it back on the client.
ajax
function verify() {
$.ajax({
type: "POST",
url: "Register.aspx/verifyImage",
data: '{text: "' + $("#<%=TextBox4.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert(response.d)
},
failure: function(response) {
alert(response.d);
}
});
}
C# webmethod
[WebMethod]
public void verifyImage(string text)
{
string imageString = Session["imageString"].ToString();
if (imageString.Equals(text))
{
Response.Write("<script>alert('Memeber Page');</script>");
}
else
{
Response.Write("<script>alert('Incorrect');</script>");
}
}
Page controls
<div style="height: 50px">
<asp:Image ID="Image1" runat="server" />
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
<input id="Button1" type="button" value="Submit" onclick="verify()"/>
</div>
Debug Output
"name":"POST /Register.aspx/verifyImage","duration":"00:00:00.0161020","success":true,"responseCode":"401","url":"http://localhost:54506/Register.aspx/verifyImage","properties":{"DeveloperMode":"true","_MS.ProcessedByMetricExtractors":"(Name:'Requests', Ver:'1.0')
I'm new to ajax and am building an image verifier page. I want to compare the image text to asp textbox text using ajax to send the textbox text to a web method in the code behind. In the output, the ajax call writes success: true, but returns a 401 (unauthorized) code. What am I doing wrong? At this point I'm just trying to get the call to work and will fill in the webmethod more later.
I am trying to get access and find text-box in GridView using javascript but i am getting an error: 'The name txt_UID' does not exist in the current context'. Everything worked fine when my text-box was outside of the GridView. Here is my text-box in the gridview and my gridview is called GridView1:
<asp:TemplateField ItemStyle-Width="150px" HeaderText="User Assigned">
<ItemTemplate>
<asp:TextBox ID="txt_UID" runat="server" Text='<%# Eval("UID")%>'
CssClass="AutoCompleteTextBox" Width="130px" BackColor="LightGoldenrodYellow"></asp:TextBox>
</ItemTemplate>
<ItemStyle Width="150px" />
</asp:TemplateField>
Here is my JavaScript:
<script type ="text/javascript">
function setAutoComplete() {
var textBoxes = document.getElementsByClassName("AutoCompleteTextBox");
for (var i = 0; i < textBoxes.length; i++) {
addAutoComplete(textBoxes[i].id);
}
}
</script>
<script type="text/javascript">
function addAutoComplete(textBoxId) {
$("#" + textBoxId).autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/Service.asmx/GetUserNames") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("#<%=hfUserId.ClientID %>").val(i.item.val);
},
minLength: 1
});
};
<script type ="text/javascript">
$(document).ready(function () { setAutoComplete(); });
</script>
The problem is your GridView creates a TextBox on each row. There is no "txt_UID" control outside of the GridView. That is what your error message is telling you.
Your JavaScript function is designed to work with one TextBox. I imagine you want the AutoComplete to work on ALL TextBox controls in the GridView.
My suggestion would be to change the JavaScript function to take a parameter with the TextBox ID and then add a CSS class to each TextBox, and finally make a wrapper JavaScript function that will enumerate the TextBox controls using getElementsByClassName, and call that wrapper function on DOM ready.
Here's what it will look like:
Add CSS class to the TextBoxes:
<asp:TemplateField ItemStyle-Width="150px" HeaderText="User Name">
<ItemTemplate>
<asp:TextBox ID="txt_UID" runat="server" Text='<%# Eval("UID")%>'
CssClass="AutoCompleteTextBox" Width="130px" BackColor="LightGoldenrodYellow"></asp:TextBox>
</ItemTemplate>
<ItemStyle Width="150px" />
</asp:TemplateField>
New JavaScript function:
function setAutoComplete()
{
var textBoxes = document.getElementsByClassName("AutoCompleteTextBox");
for (var i = 0; i < textBoxes.length; i++)
{
addAutoComplete(textBoxes[i].id);
}
}
Next, make your other JavaScript into a function that takes a parameter (the id):
function addAutoComplete(textBoxId) {
$("#" + textBoxId).autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/Service.asmx/GetUserNames") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("#<%=hfUserId.ClientID %>").val(i.item.val);
},
minLength: 1
});
};
Finally, your on ready code changes to just call the wrapper function you created:
$(document).ready(function () { setAutoComplete(); });
Bonus: Here's a way to do it with jQuery only:
(just requires the CSS class on the TextBoxes)
$(document).ready(function () {
$.each($(".AutoCompleteTextBox"), function (i, textBox) {
textBox.autocomplete( /* your code */);
})
});
Your Gridview will be rendered as Table and your control will be contained in cell of table. You can give a try to following.
<script type=”text/javascript”>
$(document).ready(function(){
tblTable=document.getElementById(‘<<Client ID of the GridView>>’);
Cell=tblTable.rows[i].cells[j];//i and j are locations of that cell.
FirstControl = Cell.childNodes[0];
});
</script>
replace <<Client ID of the GridView>> with id of your GridView
you can use name attribute and the grid id to find it:
<asp:TextBox ID="txt_UID" name="mytextbox" runat="server" Text='<%# Eval("UID")%>'
Width="130px" BackColor="LightGoldenrodYellow"></asp:TextBox>
the javascript part:
$("#<%=MyGrid.ClientID %>[name=mytextbox]").autocomplete({});
Im using jQuery Autocomplete using Web Service in ASP.Net.I've used the autocomplete to filter employeecode.When the page loads autocomplete works fine,but after when i click the search button autocomplete is not working properly.
I think the problem lies in document.ready function,so when the page loads it works fine,But i've to use autocomplete after the buttonclick event also.
How can i do this ???
Heres my jQuery Autocomplete
<link href="../AutoComplete/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="../AutoComplete/jquery.min.js" type="text/javascript"></script>
<script src="../AutoComplete/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#<%=txtEmpcode.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/MyWebService.asmx/FetchEmpCode") %>',
data: "{ 'Empcode': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[1],
//val: item
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
minLength: 1
});
});
</script>
Markup
<td align="right">
<asp:Label ID="lblEmpCodeSrch" runat="server" Text="EmpCode" CssClass="label"> </asp:Label>
</td>
<td>
<asp:TextBox ID="txtEmpCodeSrch" runat="server" Width="250px" ToolTip="Enter Employeecode"></asp:TextBox>
<asp:Button ID="bttnSearch" runat="server" CssClass="submit" Height="23px" Text="Search" onclick="bttnSearch_Click" />
</td>
ButtonSearch Codebehind
protected void bttnSearch_Click(object sender, EventArgs e)
{
clsEmp.EMPLOYEEID =txtEmpCodeSrch.Text.Trim()==""? 0:Convert.ToInt32(hFieldEmpId.Value);
DataTable dtEmp = clsEmp.GetDetails();
if (dtEmp.Rows.Count > 0)
{
hFieldEmpId.Value = "";
// txtEmpCodeSrch.Text = "";
if (ViewState["Sort"] != null)
{
DataView dView = new DataView(dtEmp);
dView.Sort = ViewState["Sort"].ToString();
gdView.DataSource = dView;
gdView.DataBind();
}
else
{
gdView.DataSource = dtEmp;
gdView.DataBind();
}
}
}
When you have an UpdatePanel, after the update of the data, you also need to re-initialize the javascript, because the old one is not longer working, because the struct of your html page have change, the dom have change.
The UpdatePanel is giving some function to do that on client side, and your code will be as:
<script type="text/javascript">
// if you use jQuery, you can load them when dom is read.
$(document).ready(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
// Place here the first init of the autocomplete
InitAutoCompl();
});
function InitializeRequest(sender, args) {
}
function EndRequest(sender, args) {
// after update occur on UpdatePanel re-init the Autocomplete
InitAutoCompl();
}
function InitAutoCompl() {
$("#<%=txtEmpcode.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/MyWebService.asmx/FetchEmpCode") %>',
data: "{ 'Empcode': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[1],
//val: item
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
minLength: 1
});
}
</script>
I tell you that I could solve the problem by adding a Triggers within the UpdatePanel tag, thus achieves the desired behavior in my case. I hope you can serve you as me helped me.
<ajax:UpdatePanel>
<ContentTemplate>
//My label fire autocomplete
<asp:TextBox id="MyLabelForAutoComplete" runat="server"/>
// Other Html Tags...
<Triggers>
<ajax:PostBackTrigger ControlID="MyLabelForAutoComplete">
</Triggers>
</ajax:UpdatePanel>
I have 2 dropdownlist which is already binded on pageload , i want to rebind these two dropdownlist after firing a ajax function.Here i have written a sql server stored procedure to get the data which is needed to dropdownlists.But how i will get the value to dropdownlist,so that it can bind the new data using ajax function.The screen is developed by using Asp.net C# coding.
Here is the drop down list of the asp.net
<asp:DropDownList id="ddlCourse" runat="server" AutoPostBack="false"
Height="28px" title="Select Course" Width="290px"
></asp:DropDownList>
and here is the jquery method that is calling the web service method
function BindCourse() {
$.ajax({
type: "POST",
url: "/WebService/CollegeWebService.asmx/GetCourseDetails",
data: "{}",
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnCoursePopulated,
error: function (xml, textStatus, errorThrown) {
alert('error');
alert(xml.status + "||" + xml.responseText);
}
});
}
This is the method to That is used in the ajex call method and call the PopulateControl method to bind the Drop down List
function OnCoursePopulated(response) {
PopulateControl(response.d, $('#<%=ddlCourse.ClientID %>'));
}
Here is the description of the PopulateControl Method
function PopulateControl(list, control) {
if (list.length > 0) {
control.removeAttr("disabled");
control.empty().append('<option selected="selected" value="0">Please select</option>');
$.each(list, function () {
control.append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
else {
control.empty().append('<option selected="selected" value="0">Not available<option>');
}
}
Thus you finally bind the drop down list
You can try the following as a demo. Server side DropDownLists are replaced with HTML select elements so that exception "Invalid postback or callback argument" doesn't happen.
Drawback in this demo is that the values are not restored on form after postback. You can put this inside a form in Default.aspx:
<script type="text/javascript"
src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function populate(populateInitial) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/Default.aspx/populate',
data: "{'populateInitial': '" + populateInitial + "'}",
dataType: "json",
async: false,
success: function(result) {
var ddlItems = document.getElementById('ddlItems');
ddlItems.options.length = 0;
$.each(result.d, function(key, item)
{ ddlItems.options[key] = new Option(item); });
}
});
}
</script>
<form id="form1" runat="server">
<div>
<select id="ddlItems" name="ddlItems">
</select>
<br />
<input type="button" onclick="populate('0');" value="Change values" />
<br />
Selected item:
<asp:Label ID="lblSelectedItem" runat="server" Text=""> </asp:Label>
<br />
<asp:Button ID="Button1" runat="server"
Text="Write out selected item text" />
</div>
<script type="text/javascript">
populate('1');
</script>
And you put these methods inside Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
lblSelectedItem.Text = Request["ddlItems"].ToString();
}
}
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static List<string> populate(string populateInitial)
{
if (populateInitial == "1")
return (new string[] { "a", "b" }).ToList();
else
return (new string[] { "c", "d", "e", "f" }).ToList();
}
You should make Ajax call to some sort of page (I advice you to add Generic Hanlder) which responses xml or json or even html, of drop down values and textfield values, than read it in javascript jquery and generate html for your drop down which is the following
<select id="ddl">
<option value="value">text</option>
</select>
you should read "value" & text and generate this> <option value="value">text</option>
and append to ddl