How to get associated data of 2nd dropdownlist when user selects items from 1st dropdownlist?
This article is about how to get associated data of second dropdownlist when user selects particular items from first dropdownlist using JQuery in MVC4 application. There can be multiple client applications use same web api hence we can implement one client application and one web api template for demo purpose.
Description- If you want to load data dynamically in second control based on your selection then filters have to be added.
This functionality can be achieved with the help of JQuery.
In this example, lets say customer has ordered few products and we have two dropdownlist. One is for Customers and another is for products.
Now, after selecting any particular customer, we need to retrieve data of products of that particular customer hence we need to send customer id and fetch the data and display it in second dropdownlist.
$('select').change(function (e) {
var user_selected_id = $(this).attr('id');
//It will return, if drop down has been selected which is other than DrpCust_
if (user_selected_id.indexOf("DrpCust_") != 0) return;
var CustId = $(this).val();
var OrderId = user_selected_id.substr(user_selected_id.indexOf("_") + 1);
var request = $.ajax({
url: "/yournamespacename/yourcontrollername/GetAssociatedData",
dataType: "json",
cache: false,
data: { "CustomerId": CustId }
})
request.fail(function (jqXHR, textStatus) { alert("Request failed: " + textStatus); });
request.success(function (data) {
$("#DrpProducts" + OrderId).empty();
$.each(data, function (i, item) {
$("#DrpProducts" + OrderId).append($('<option></option>').val(data[i].ProductId).html(data[i].ProductName));
});
});
});
In ActionResult GetAssociatedData, you can write data retrival logic similar to this.
public ActionResult GetAssociatedData(int CustomerId)
{
List lstProducts = GetProductsFromCustomers(CustomerId);
if (lstProducts!= null)
return Json(lstProducts, JsonRequestBehavior.AllowGet);
else
return Json(new { Message = "Error Found!" }, JsonRequestBehavior.AllowGet);
}
private List GetProductsFromCustomers(int CustomerId)
{
your_classname ans = new your_classname();
HttpClient client = new HttpClient();
var forTask = client.GetAsync("http://" + ServerName + "/yourwebapinamespace/api/Product?" + CustomerId)
.ContinueWith((myTask) =>
{
var generatedResponse = myTask.Result;
if (generatedResponse.StatusCode == HttpStatusCode.OK)
{
var varForread = generatedResponse.Content.ReadAsAsync<List>();
varForread.Wait();
ans = varForread.Result;
}
});
forTask.Wait();
return ans;
}
You have to write web api for Product and pass particular CustomerId to retrieve data.
You can test web api through fiddler.