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
Related
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 have to pass bulk array values to code behind (cs) using ajax i had researched a lot and used this code but it didnot worked for me below is the code that i used what i need is i need to pass bulk array values in code behind(cs) using ajax
JS
<head runat="server">
<title></title>
<script>
function foo() {
var values = ["1,", "2", "3"];
// Make the ajax call
$.ajax({
type: "POST",
url: "Default.aspx/Done", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ arr: values }),
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" UseSubmitBehavior="false" OnClientClick="return foo();" />
</div>
</form>
</body>
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
namespace PassingValueFromJavascriptToCs
{
public partial class WebForm3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static void done(string[] ids)
{
String[] a = ids;
// Do whatever processing you want
// However, you cannot access server controls
// in a static web method.
}
}
}
First of all the button for aspx is sending your aspx form to a postback so that you would need to change the aspx like this
<script>
function foo() {
var values = ["1,", "2", "3"];
// Make the ajax call
$.ajax({
type: "POST",
url: "Default.aspx/Done", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ arr: values }),
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" UseSubmitBehavior="false" OnClientClick="return foo();" />
</div>
</form>
</body>
The reason the foo method returns false that you dont want to make your button start a postback. I also added another property UseSubmitBehavior="false" to guarantee it.
The scripts section i changed the values object to a real array and then when sending data , i converted it to json with values object inside. This code will work in your example just fine
Edit : For the working version on my tests
The aspx page (trimmed details to the master page)
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<script>
function test() {
var values = ["1,", "2", "3"];
// Make the ajax call
$.ajax({
type: "POST",
url: "Default.aspx/test", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ arr: values }),
dataType: "json",
success: function (result) {
debugger;
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
return false;
}
</script>
<asp:Button ID="Button3" UseSubmitBehavior="false" OnClientClick="return test();" runat="server" Text="Deneme" />
</asp:Content>
The RouteConfig and original method
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
//settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);
}
}
[WebMethod]
public static void test(string[] arr)
{
}
Well at least one issue is your url is "Default.aspx/Done" but the method appears to be on WebForm3.aspx/Done.
What actually happens with your code? Does it error?
<div style="position: absolute; top: 841px; left: 12%;">
<asp:TextBox ID="txtHotel" runat="server" CssClass="search_hot_txtbox" ></asp:TextBox>
</div>
<br>
<script type="text/javascript">
$(function fnc() {
$(".search_hot_txtbox").autocomplete({
source: function(request, response) {
$.ajax({
url: "hotel-result.aspx/BindDatatoDropdown",
data: "{ 'cn': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
value: item.HotelName
}
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// alert(textStatus);
}
});
},
minLength: 2
});
});
</script>
protected void chk3_CheckedChanged(object sender, EventArgs e)
{
if (Session["List"] != null)
UCPager1.GetItemsControl(1, 5, 0, chk3star.Checked, chk2star.Checked, chk1star.Checked, chk4star.Checked, chk5star.Checked, chkP1.Checked, chkP2.Checked, chkP3.Checked, chkP4.Checked, chkP5.Checked, txtHotel.Text, spP1.InnerText, spP2.InnerText, spP3.InnerText, spP4.InnerText, spP5.InnerText, new Repeater(), chkP6.Checked, chkP7.Checked, chkP8.Checked, spP6.InnerText, spP7.InnerText, spP8.InnerText);
else
UCPager1.GetItems();
}
You need here to make a post back, when you press "enter" on the textbox the browser make the postback, but if you wish to make it with javascript you need to fire up a button control.
So I place a button control, and I can even have it hidden with css as:
<div style="position: absolute; top: 841px; left: 12%;">
<asp:TextBox ID="txtHotel" runat="server" CssClass="search_hot_txtbox" onkeydown="return SendKeyEnterTo(event, 'btnGo');" />
<asp:Button runat="server" ID="btnGo" Text="search" onclick="btnSearch_Click" style="display:none;" ClientIDMode="Static" />
</div>
and then using this simple javascript I read the "enter" key from the textbox and trigger that post back of the input control.
function SendKeyEnterTo(e, IdToClick)
{
// look for window.event in case event isn't passed in
if (window.event)
{
e = window.event;
}
if (e.keyCode == 13)
{
document.getElementById(IdToClick).click();
return false;
}
else
{
return true;
}
}
This onkeydown="return SendKeyEnterTo(event, 'btnGo');" is important to read the text box input, and the ClientIDMode="Static" on the button is important to keep the same id when its rendered.
Also, please note, this code is run together with the autocomplete, and I have tested and use it.
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 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();