Hello All.
I need some help regarding binding the data in a json array to an html dropdownlist. I have the C# codes for fetching the data from the database working fine. I have checked it using debugger. But my script for binding the data to the control isn't working
at all. I cannot understand why. I am using jquery library 1.4.1.min.js. I am posting some of the code blocks here for you to analyse and hopefully spot the mistake I am committing.
I this application I am supposed to first fetch the department names and their ids like Software:1, Hardware:2, HR:3,................... and so on and bind them to the first control. next on selecting any one department I am supposed to fill the second control with names of employees belonging to that department. This is what my requirement is. Server.aspx is the url of the page where all the ajax requests are being dealt with. The coding there has been done in C# and is wworking fine. Here is the code block for Server.aspx.cs
public partial class Server : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Buffer = true;
Response.Write(" ");
string action = AJAX.GetParameter("action", new string[] { "department","employee"});
switch (action.ToLower())
{
case "department": DepartmentModule(); break;
case "employee": EmployeeModule(); break;
}
}
public void DepartmentModule()
{
string action = AJAX.GetParameter("method", new string[] { "populatedepartment"});
switch (action.ToLower())
{
case "populatedepartment":
List<BLL_Department> deps = BLL_Department.GetDepartmentByName(AJAX.GetParameter("searchtext", "Search Text"));
foreach (BLL_Department dep in deps)
AJAX.Success("{\"DepartmentList\":" + JsonConvert.SerializeObject(deps.ToArray()) + "}");
break;
}
}
public void EmployeeModule()
{
string action = AJAX.GetParameter("method", new string[] {"employeelist" });
switch (action.ToLower())
{
case "employeelist":
List<BLL_Employee> emps = BLL_Employee.GetEmployees(int.Parse(AJAX.GetParameter("dep_id")));
foreach (BLL_Employee emp in emps)
AJAX.Success("{\"LoadEmployee\":" + JsonConvert.SerializeObject(emps.ToArray()) + "}");
break;
}
}
public class LabelValuePair
{
public readonly string Label;
public readonly object Value;
public LabelValuePair(string lab, object val)
{
Label = lab;
Value = val;
}
}
//Convenience class for encapsulating & standardising all AJAX returns
private class AJAX
{
public static void Error(string msg)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.StatusCode = 500;
HttpContext.Current.Response.ContentType = "text/html";
HttpContext.Current.Response.Write(msg);
}
public static void Error(Exception ex)
{
if (ex is AJAXUsageError)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "text/html";
HttpContext.Current.Response.Write("Invalid Usage <br/>" + ex.Message);
}
else
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.StatusCode = 500;
HttpContext.Current.Response.ContentType = "text/html";
HttpContext.Current.Response.Write("{\"Message\":\"" + ex.Message + "\",\"StackTrace\":\"" + ex.StackTrace + "\"}");
}
}
public static void Success(string data)
{
HttpContext.Current.Response.Write(data);
}
public static void Success(object data)
{
HttpContext.Current.Response.Write(JsonConvert.SerializeObject(data));
}
/// <summary>
/// Gets an expected parameter from QueryString or Post
/// If parameter not found, or values not allowed, then proceessing stops and
/// an error is returned with usage message
/// </summary>
/// <param name="paramName">Expected parameter name</param>
/// <param name="allowedValues">Array of allowed values</param>
public static string GetParameter(string paramName, string[] allowedValues)
{
string val = HttpContext.Current.Request[paramName];
bool match = false;
if (val != null)
{
foreach (string v in allowedValues)
{
if (v.ToLower() == val.ToLower())
{
match = true;
break;
}
}
}
if (val == null || !match)
{
//incorrect usage
throw new AJAXUsageError(paramName + " is a required parameter and must have values of " + JsonConvert.SerializeObject(allowedValues));
}
return val;
}
/// <summary>
///
/// </summary>
/// <param name="paramName"></param>
/// <returns></returns>
public static string GetParameter(string paramName)
{
string val = HttpContext.Current.Request[paramName];
if (val == null)
{
//incorrect usage
throw new AJAXUsageError(paramName + " is a required parameter");
}
return val;
}
/// <summary>
/// Get parameter
/// </summary>
/// <param name="paramName"></param>
/// <param name="paramDesc">Description of the parameter</param>
/// <returns></returns>
public static string GetParameter(string paramName, string paramDesc)
{
string val = HttpContext.Current.Request[paramName];
if (val == null)
{
//incorrect usage
throw new AJAXUsageError(paramName + " is a required parameter (" + paramDesc + ")");
}
return val;
}
/// <summary>
/// Get GetParameter Including Null values , for
/// </summary>
/// <param name="paramName"></param>
/// <param name="paramDesc">Description of the parameter</param>
/// <returns></returns>
public static string GetParameterIncludingNull(string paramName, string paramDesc)
{
string val = HttpContext.Current.Request[paramName];
return val;
}
}
private class AJAXUsageError : Exception
{
public AJAXUsageError(string message)
: base(message)
{
}
}
}
Hope to get some active help on this example soon enough. I am a complete beginner in jquery, so I request you humbly to step forward and help me out.
Thanks in Anticipation.
There are more wonders in this world of ours than you can wonder.....
Change the getJSON to $.ajax adn add a error method and check what error you are getting. Anyway there are few working examples for cascading dropdownlist-
Thanks for the reply. I tried using $.ajax but to no avail.
Could you please direct me as to how to add an error method to check what response I'm getting. I don't know anything about jquery. Please help me. This means a lot to me. I can share this simple application with you and provide you the link if you want
to try it out yourself. Some code wrt the jquery I have already developed would be immensely helpful. remember I have to send the action and method parameters to server.aspx page. So whatever is to be done has to be incorporated in this structure I have developed.
Look forward eagerly to your reply.
There are more wonders in this world of ours than you can wonder.....
The link to this example isn't quite what I am looking for. It's too simple and straightforward. I am looking for something that uses GetJson and send parameters like action, method, searchstring to the server page.
Sent you a pr. message. Please check.
Thanks.
There are more wonders in this world of ours than you can wonder.....
Is there nobody who can solve the problem? Surely there ought to be someone who knows this approach. I request you to please show me the way. I made as much progress as I could with my miniscule knowledge of jQuery. For the rest I am dependant on you. Please
download the practise app. and at least try to analyse what I have done or where I have gone wrong.
For someone good enough it will barely take 15 minutes. Please help me. I need it badly.
Thanks.
There are more wonders in this world of ours than you can wonder.....
Have you used a tool like Fiddler to see the requests going out and back? What does the response look like? If it what you expedct to be returned? Are there any error messages in the console? And you are using a verison of jQuery that is 4 versions behind.
You should upgrade in the near future.
PGChoudhury
Member
11 Points
131 Posts
JSON JQUERY HELP NEEDED [Critical ----]
Oct 08, 2012 07:47 AM|LINK
Hello All.
I need some help regarding binding the data in a json array to an html dropdownlist. I have the C# codes for fetching the data from the database working fine. I have checked it using debugger. But my script for binding the data to the control isn't working at all. I cannot understand why. I am using jquery library 1.4.1.min.js. I am posting some of the code blocks here for you to analyse and hopefully spot the mistake I am committing.
<head runat="server"> <title></title> <script language="javascript" type="text/javascript" src="Scripts/jquery.js"></script> <script src="Scripts/jquery.min.js" type="text/javascript" language="javascript"></script> <script language="javascript" type="text/javascript"> $(document).ready(function () { PopulateDepartmentDropDown(); }); function PopulateDepartmentDropDown() { jQuery.getJSON("Server.aspx", { "action": "department", "method": "populatedepartment", "searchtext": "" }, function (response) { if (!response) return; jQuery('#ddlDep').html(''); jQuery('#ddlDep').append("<option value='-1'>-- Please Select --</option>"); jQuery.each(eval(response.DepartmentList), function () { jQuery('#ddlDep').append("<option value='" + this.dep_id + "'>" + this.dep_name + "</option>"); }); }); } function PopulateEmployeeDropDown() { if (jQuery('#ddlDep').val() == "-1") { jQuery('#ddlEmp').html(''); jQuery('#ddEmp').append("<option value='-1'>-- Please Select --</option>"); return; } jQuery.getJSON("Server.aspx", { "action": "employee", "method": "employeelist", "dep_id": jQuery('#ddlDep').val() }, function (response) { if (!response) return; jQuery('#ddlEmp').html(''); jQuery('#ddlEmp').append("<option value='-1'>-- Please Select --</option>"); jQuery.each(eval(response.EmployeeList), function () { jQuery('#ddlEmp').append("<option value='" + this.emp_id + "'>" + this.emp_name + "</option>"); }); }); } </script> </head> <body> <form id="form1" runat="server"> <div> <img alt="" height="400px" src="Apple%20Mac%20OS%20X%20Lion%20Clean%20Wallpaper.jpg" width="400px" /><br /> Select Department <select id="ddlDep" name="ddlDep" onchange="javascript:PopulateEmployeeDropDown();"> <option value="-1">---Select---</option> </select> <br /> Select Employee <select id="ddlEmp" name="ddlEmp" onchange="javascript:ShowEmployeeDetails();"> <option value="-1">---Select---</option> </select> <br /> <div id="output" style="background-color: #D0FDE8"> </div> </div> </form> </body>I this application I am supposed to first fetch the department names and their ids like Software:1, Hardware:2, HR:3,................... and so on and bind them to the first control. next on selecting any one department I am supposed to fill the second control with names of employees belonging to that department. This is what my requirement is. Server.aspx is the url of the page where all the ajax requests are being dealt with. The coding there has been done in C# and is wworking fine. Here is the code block for Server.aspx.cs
public partial class Server : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Response.Buffer = true; Response.Write(" "); string action = AJAX.GetParameter("action", new string[] { "department","employee"}); switch (action.ToLower()) { case "department": DepartmentModule(); break; case "employee": EmployeeModule(); break; } } public void DepartmentModule() { string action = AJAX.GetParameter("method", new string[] { "populatedepartment"}); switch (action.ToLower()) { case "populatedepartment": List<BLL_Department> deps = BLL_Department.GetDepartmentByName(AJAX.GetParameter("searchtext", "Search Text")); foreach (BLL_Department dep in deps) AJAX.Success("{\"DepartmentList\":" + JsonConvert.SerializeObject(deps.ToArray()) + "}"); break; } } public void EmployeeModule() { string action = AJAX.GetParameter("method", new string[] {"employeelist" }); switch (action.ToLower()) { case "employeelist": List<BLL_Employee> emps = BLL_Employee.GetEmployees(int.Parse(AJAX.GetParameter("dep_id"))); foreach (BLL_Employee emp in emps) AJAX.Success("{\"LoadEmployee\":" + JsonConvert.SerializeObject(emps.ToArray()) + "}"); break; } } public class LabelValuePair { public readonly string Label; public readonly object Value; public LabelValuePair(string lab, object val) { Label = lab; Value = val; } } //Convenience class for encapsulating & standardising all AJAX returns private class AJAX { public static void Error(string msg) { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.StatusCode = 500; HttpContext.Current.Response.ContentType = "text/html"; HttpContext.Current.Response.Write(msg); } public static void Error(Exception ex) { if (ex is AJAXUsageError) { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ContentType = "text/html"; HttpContext.Current.Response.Write("Invalid Usage <br/>" + ex.Message); } else { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.StatusCode = 500; HttpContext.Current.Response.ContentType = "text/html"; HttpContext.Current.Response.Write("{\"Message\":\"" + ex.Message + "\",\"StackTrace\":\"" + ex.StackTrace + "\"}"); } } public static void Success(string data) { HttpContext.Current.Response.Write(data); } public static void Success(object data) { HttpContext.Current.Response.Write(JsonConvert.SerializeObject(data)); } /// <summary> /// Gets an expected parameter from QueryString or Post /// If parameter not found, or values not allowed, then proceessing stops and /// an error is returned with usage message /// </summary> /// <param name="paramName">Expected parameter name</param> /// <param name="allowedValues">Array of allowed values</param> public static string GetParameter(string paramName, string[] allowedValues) { string val = HttpContext.Current.Request[paramName]; bool match = false; if (val != null) { foreach (string v in allowedValues) { if (v.ToLower() == val.ToLower()) { match = true; break; } } } if (val == null || !match) { //incorrect usage throw new AJAXUsageError(paramName + " is a required parameter and must have values of " + JsonConvert.SerializeObject(allowedValues)); } return val; } /// <summary> /// /// </summary> /// <param name="paramName"></param> /// <returns></returns> public static string GetParameter(string paramName) { string val = HttpContext.Current.Request[paramName]; if (val == null) { //incorrect usage throw new AJAXUsageError(paramName + " is a required parameter"); } return val; } /// <summary> /// Get parameter /// </summary> /// <param name="paramName"></param> /// <param name="paramDesc">Description of the parameter</param> /// <returns></returns> public static string GetParameter(string paramName, string paramDesc) { string val = HttpContext.Current.Request[paramName]; if (val == null) { //incorrect usage throw new AJAXUsageError(paramName + " is a required parameter (" + paramDesc + ")"); } return val; } /// <summary> /// Get GetParameter Including Null values , for /// </summary> /// <param name="paramName"></param> /// <param name="paramDesc">Description of the parameter</param> /// <returns></returns> public static string GetParameterIncludingNull(string paramName, string paramDesc) { string val = HttpContext.Current.Request[paramName]; return val; } } private class AJAXUsageError : Exception { public AJAXUsageError(string message) : base(message) { } } }Hope to get some active help on this example soon enough. I am a complete beginner in jquery, so I request you humbly to step forward and help me out.
Thanks in Anticipation.
Mikesdotnett...
All-Star
154852 Points
19855 Posts
Moderator
MVP
Re: JSON JQUERY HELP NEEDED [Critical ----]
Oct 08, 2012 11:00 AM|LINK
Try using the jQuery in this article: http://www.mikesdotnetting.com/Article/196/WebMatrix-jQuery-Cascading-Dropdown-Lists. The actual example is a .cshtml file, but the jQuery is the same regardless.
Beginning ASP.NET Web Pages with WebMatrix | My Site | Twitter
asteranup
All-Star
30184 Points
4906 Posts
Re: JSON JQUERY HELP NEEDED [Critical ----]
Oct 09, 2012 04:23 AM|LINK
Hi,
Change the getJSON to $.ajax adn add a error method and check what error you are getting. Anyway there are few working examples for cascading dropdownlist-
http://delicious.com/anupdg/cascading
Anup Das Gupta
Mark as Answer if you feel so. Visit My Blog
PGChoudhury
Member
11 Points
131 Posts
Re: JSON JQUERY HELP NEEDED [Critical ----]
Oct 09, 2012 03:33 PM|LINK
Hi.
Thanks for the reply. I tried using $.ajax but to no avail.
Could you please direct me as to how to add an error method to check what response I'm getting. I don't know anything about jquery. Please help me. This means a lot to me. I can share this simple application with you and provide you the link if you want to try it out yourself. Some code wrt the jquery I have already developed would be immensely helpful. remember I have to send the action and method parameters to server.aspx page. So whatever is to be done has to be incorporated in this structure I have developed.
Look forward eagerly to your reply.
postonoh
Member
498 Points
259 Posts
Re: JSON JQUERY HELP NEEDED [Critical ----]
Oct 09, 2012 04:49 PM|LINK
function PopulateDepartmentDropDown() { jQuery.getJSON("Server.aspx ", { "action": "department", "method": "populatedepartment", "searchtext": "" }, function (response) { if (!response) return; jQuery('#ddlDep').html(''); jQuery('#ddlDep').append("<option value='-1'>-- Please Select --</option>"); jQuery.each(eval(response.DepartmentList), function () { jQuery('#ddlDep').append("<option value='" + this.dep_id + "'>" + this.dep_name + "</option>"); }); }); }function PopulateDepartmentDropDown() { jQuery.getJSON("Server.aspx/DepartmentModule", { "action": "department", "method": "populatedepartment", "searchtext": "" }, function (response) { if (!response) return; jQuery('#ddlDep').html(''); jQuery('#ddlDep').append("<option value='-1'>-- Please Select --</option>"); jQuery.each(eval(response.DepartmentList), function () { jQuery('#ddlDep').append("<option value='" + this.dep_id + "'>" + this.dep_name + "</option>"); }); }); }public void DepartmentModule() { string action = AJAX.GetParameter("method", new string[] { "populatedepartment"}); switch (action.ToLower()) { case "populatedepartment": List<BLL_Department> deps = BLL_Department.GetDepartmentByName(AJAX.GetParameter("searchtext", "Search Text")); foreach (BLL_Department dep in deps) AJAX.Success("{\"DepartmentList\":" + JsonConvert.SerializeObject(deps.ToArray()) + "}"); break; } }[WebMethod(true)] public void DepartmentModule() { string action = AJAX.GetParameter("method", new string[] { "populatedepartment"}); switch (action.ToLower()) { case "populatedepartment": List<BLL_Department> deps = BLL_Department.GetDepartmentByName(AJAX.GetParameter("searchtext", "Search Text")); foreach (BLL_Department dep in deps) AJAX.Success("{\"DepartmentList\":" + JsonConvert.SerializeObject(deps.ToArray()) + "}"); break; } }asteranup
All-Star
30184 Points
4906 Posts
Re: JSON JQUERY HELP NEEDED [Critical ----]
Oct 10, 2012 05:27 AM|LINK
Hi,
You can chose anyone from my previous link like-
http://forums.asp.net/p/1717977/4587810.aspx/1?Re+JQuery+AJAX+call+to+page+method+not+working
Anup Das Gupta
Mark as Answer if you feel so. Visit My Blog
PGChoudhury
Member
11 Points
131 Posts
Re: JSON JQUERY HELP NEEDED [Critical ----]
Oct 10, 2012 09:44 AM|LINK
Hi.
The link to this example isn't quite what I am looking for. It's too simple and straightforward. I am looking for something that uses GetJson and send parameters like action, method, searchstring to the server page.
Sent you a pr. message. Please check.
Thanks.
PGChoudhury
Member
11 Points
131 Posts
Re: JSON JQUERY HELP NEEDED [Critical ----]
Oct 10, 2012 09:46 AM|LINK
For anyone who wants to have a first hand look at what I have done and sort me out, here's a link to my project files:::
https://www.box.com/s/6a7pnfgazkm3cv5yomly
Thanks.
PGChoudhury
Member
11 Points
131 Posts
Re: JSON JQUERY HELP NEEDED [Critical ----]
Oct 17, 2012 03:20 PM|LINK
Is there nobody who can solve the problem? Surely there ought to be someone who knows this approach. I request you to please show me the way. I made as much progress as I could with my miniscule knowledge of jQuery. For the rest I am dependant on you. Please download the practise app. and at least try to analyse what I have done or where I have gone wrong.
For someone good enough it will barely take 15 minutes. Please help me. I need it badly.
Thanks.
A1ien51
All-Star
29935 Points
5821 Posts
Re: JSON JQUERY HELP NEEDED [Critical ----]
Oct 18, 2012 01:00 PM|LINK
Have you used a tool like Fiddler to see the requests going out and back? What does the response look like? If it what you expedct to be returned? Are there any error messages in the console? And you are using a verison of jQuery that is 4 versions behind. You should upgrade in the near future.