jquery ajax to bind dropdownlist MVC - asp.net-mvc

I have a 2 dropdownlist, I have to bind the 2nd one based on the Id I got from first dropdown. in the first dropdown I added OnChange event.
function onChange() {
var variantDropDown = $('#VariantName');
$.ajax({
url: '/Admin/CustomProductPinCodesManagement/GetProductVarinats',
type: 'post',
data: { productId: $("#ProductName").data("tDropDownList").value() },
success: function (data) {
$.each(variants, function (i, variant) {
$states.append('<option value="' + variant.Id + '">' + variant.Name + '</option>');
});
},
error: function () {
alert('Error');
}
});
}
and this is the c# code .
[HttpPost]
public ActionResult GetProductVarinats(string productId)
{
var variants = _productService.GetProductVariantsByProductId(Convert.ToInt32(productId));
return Json(new { Result = true, data = variants }, JsonRequestBehavior.AllowGet);
}
but it does not work.

Use val() instead of value()
Change statement
data: { productId: $("#ProductName").data("tDropDownList").value() }
to
data: { productId: $("#ProductName").data("tDropDownList").val() }
and the success should be like
success: function (data) {
//For getting list of variants, you should access it by `data.data.variants`
//because you will get your json object in data, and for getting the value `variants`
//you should capture the `data` property of returned json object like `data.data`
$.each(data.data.variants, function (i, variant) {
$states.append('<option value="' + variant.Id + '">'+ variant.Name + '</option>');
//you can try this also for creating options
//$states.append($('<option/>').text(variant.Name).attr('value',variant.Id));
});
}
so your function should look like :
function onChange() {
var variantDropDown = $('#VariantName');
$.ajax({
url: '/Admin/CustomProductPinCodesManagement/GetProductVarinats',
type : 'post',
data: { productId: $("#ProductName").data("tDropDownList").val() },
success: function (data) {
$.each(data.data.variants, function (i, variant) {
$states.append($('<option/>').text(variant.Name).attr('value',variant.Id));
});
},
error: function () {
alert('Error');
}
});
}

AcidMedia has a library called TTControls which uses Telerik and you can use the TTControls.LinkedDropDown control which solves this problem.

Related

How to avoid multiple ajax call from the Jquery Autocomplete ? Using Cache

I am using jquery automcomplete with the Ajax call but what i want is if part is present in the json data fetched by the ajax on first call then i want to return that data as it is without giving the ajax call i have tried it as below
function SearchText() {
var cache = {};
$("#txtItem").autocomplete({
source: function (request, response) {
var term = request.term;
$.each(cache, function (index, value) {
$.each(value, function (index, value) {
if (value.indexOf(term) >= 0) {
response(cache[term]);
return;
}
});
});
cache = {};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "JobTagPricing.aspx/GetAutoCompleteData",
data: "{'item':'" + document.getElementById('txtItem').value + "'}",
dataType: "json",
success: function (data) {
cache[term] = data.d;
response(data.d);
},
error: function (result) {
alert("Error");
}
});
},
minLength: 3
});
}
but even if it finds the matching term in the array then also it generates the ajax call.
I m stuck here for 3 hrs now any help would be great. I have tried maxCacheLength but it is also not working.
Try this out, sometime ago i faced same problem and came up with this it might work for you
function SearchText() {
var cache = {};
var oldterm;
$("#txtItem").autocomplete({
source: function (request, response) {
if (request.term.indexOf(oldterm) >= 0) {
if (typeof (oldterm) != 'undefined') {
var data = jQuery.grep(cache[oldterm],
function (ele) {
return (ele.indexOf(request.term) >= 0);
});
response($.map(data, function (item) {
return { value: item }
}))
return;
}
} else {
cache = {};
$.ajax({
url: "JobTagPricing.aspx/GetAutoCompleteData",
data: "{ 'item': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
oldterm = request.term;
cache[request.term] = data.d;
response($.map(data.d, function (item) {
return {
value: item
}
}))
},
error: function (result) {
alert("Error");
}
});
}
},
minLength: 3,
select: function (event, ui) {
if (ui.item) {
formatAutoComplete(ui.item);
}
}
});
}
Here is a solution i found for you, It uses jQuery UI's autocomplete using cache and $.map function
function SearchText() {
var cache = {};
$("#textbox").autocomplete({
source: function(request, response) {
if (request.term in cache) {
response($.map(cache[request.term].d, function(item) {
return { value: item.value, id: item.id }
}))
return;
}
$.ajax({
url: "JobTagPricing.aspx/GetAutoCompleteData",
data: "{ 'term': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json",
dataFilter: function(data) { return data; },
success: function(data) {
cache[request.term] = data;
response($.map(data.d, function(item) {
return {
value: item.value,
id: item.id
}
}))
},
error: HandleAjaxError
});
},
minLength: 3,
select: function(event, ui) {
if (ui.item) {
formatAutoComplete(ui.item);
}
}
});
}
Hope this helps.

Ajax refresh in mvc div data

I am developing a MVC application, where I have a scenario to refresh a part of the page basically ajax...
<div id="ajax" style="width:10%;float:left">
#foreach (var item in #Model.SModel.Where(x=>x.StudentId==13))
{
<li>#Html.DisplayFor(score => item.StudentName)</li>
}
This is the div (part of the page) which I need to refresh on a button click. I have 2 js files, data.js and render.js...
data.js contains a template as follows:
makeAJAXCall =
function (url, params, callback) {
$.ajax({
type: "get",
timeout: 180000,
cache: false,
url: url,
dataType: "json",
data: params,
contentType: "application/json; charset=utf-8",
success: function (result) {
if (callback) {
callback(result);
}
},
error: function (req, status, error) {
}
return null;
}
});
};
getGrid = function () {
makeAJAXCall(urlCollection["getGridInfo"], "", function (result) {
renderer.renderGridInfo('ajax', result);
});
};
and render.js file is as follows:
renderGridInfo = function (area, data) {
$("#" + area).text(data);
};
return {
renderGridInfo: renderGridInfo
};
In the loading page on button click function as :
Service.addURL('getGridInfo', '#Html.Raw(#Url.Action("getGridInfo", "AjaxController"))');
Service.getGrid();
In the ajax controller, the code is :
public JsonResult getGridInfo()
{
return Json(model, JsonRequestBehavior.AllowGet);
}
But the problem I am facing is, the controller is returning the JsonResult , but the 'div' accepts the model and so the output is [object] [object] button click
Question: Is there any way to refresh this 'div' from the Jsondata returned by the controller?
I have to follow this type of design without using AjaxForm.
Look what happens:
1) you returns Json: return Json(model, JsonRequestBehavior.AllowGet);
2) you put returned Json object to the div's value: $("#" + area).text(data);
that's why you end up with json's representation inside div
You need to change it as follows:
1) assume you put html for that div to model's field called NewHtml
2) eptract html from the property of returned json: var returnedHtml = data.NewHtml;
3) use html() method instead of text(): $("#" + area).html(returnedHtml);

Autocomplete in Jqgrid returns Data from Server but dont know to put in View

This is my first post. stackoverflow is a wonderful place for developers. Here is my issue.
I am trying to use Autocomplete in JqGrid Edit Form. i successfully retrieved data from server using ajax call but dont know how to display it in the view. below is my code.
FrontEnd Code:
colModel :[
{name:'prf_articlename', index:'prf_articlename', width:90, editable:true, edittype:'text',
editoptions: {
dataInit:function(e){
$(e).autocomplete({
source: function(request, response,term) {
var param = request.term;
$.ajax({
url: '/Myelclass/AutoCompleteServlet.do?term='+param+"&action="+"artname",
success: function (data) {
response($.map(data, function(item) {
return {
label: item.label,
};
}));//END Success
},
});//END AJAX
},
minLength: 2,
});//END AUOTOCOMPLETE
}//END Dataint
}//END Dataint
},
BackEnd Code:
String term = request.getParameter("term");
List<AutoComplete> articlelist = prfbo.getArticleNameinEditGrid(term);
System.out.println("List Value " +articlelist.size());
JSONArray jsonOrdertanArray = JSONArray.fromObject(articlelist);
System.out.println(jsonOrdertanArray);
out.println(jsonOrdertanArray);
Any one help on this???
This is what I personally use in my project:
Inside colModel:
dataInit: function (elem) { NameSearch(elem) }},
The function:
function NameSearch(elem) {
$(elem).autocomplete({ source: '/Controller/NameSearch',
minLength: 2, autosearch: true,
select: function (event, ui) {
$(elem).val(ui.item.value);
$(elem).focus().trigger({ type: 'keypress', charCode: 13 });
}
})//$(elem).autocomplete
$(elem).keypress(function (e) {
if (!e) e = window.event;
if (e.keyCode == '13') {
setTimeout(function () { $(elem).autocomplete('close'); }, 500);
return false;
}
})//$(elem).keypress(function (e){
} //function NameSearch(elem) {
I'm also dealing with an Enter key press as well in the above function.
here is the complete code for my Autocomplete in jqgrid Edit form..
colModel :[
{name:'name', index:'name', width:90, align:'center', editable:true, hidden: false, edittype:'text',
editoptions:{
dataInit:function (elem) {
$(elem).autocomplete({
minLength: 2,
source: function(request, response,term) {
var param = request.term; //values we enter to filter autocomplete
$.ajax({
url: "myurl",
dataType: "json",
type:"GET",
success: function (data) {
response($.map(data, function(item) {
return {
//can add number of attributes here
id: item.id,
shform: item.shortform,
value: item.name,
clr : item.color, //here apart from name and id i am adding other values too
size: item.size,
remar:item.remarks,
subs: item.subs,
selec:item.selec ,
};
}));//END Response
},//END Success
});//END AJAX
},
select: function( event, ui ) {
// setting values to textbox in jqgrid edit form based on selected values
$('#textbox1').val(ui.item.id);
$('#textbox2').val(ui.item.shform);
$('#textbox3').val(ui.item.clr);
$('#textbox4').val(ui.item.size);
$('#textbox5').val(ui.item.sizeremar);
$('#textbox6').val(ui.item.subs);
$('#textbox7').val(ui.item.selec);
$('#textbox8').val(ui.item.selp);
}
});
$('.ui-autocomplete').css('zIndex',1000); // if autocomplete has misalignment so we are manually setting it
}
}, editrules :{required : true},
formoptions:{rowpos: 1, colpos: 2}
},
........
]
server code :
String term = request.getParameter("term");
List<ArticleDetails> articlelist = prfbo.getPrfArticleName(term); //DB call via BO and DAO class
System.out.println("List Value " +articlelist.size());
JSONArray jsonOrdertanArray = JSONArray.fromObject(articlelist);
System.out.println(jsonOrdertanArray);
out.println(jsonOrdertanArray);
hope some one find it useful.

Checking if all data has been returned from server in Knockout

I am displaying data from the user on the user page and i would like to notify the user once all the data has been loaded and there is no more data to retrieve from the server using knockout.
Knockout script
$.views.Roster.GetPage = function ( pageNumber) {
$.grain.Ajax.Get({
Url: Views.Roster.Properties.Url,
DataToSubmit: { pageNumber: pageNumber, id: Views.Roster.Properties.Id },
DataType: "json",
OnSuccess: function (data, status, jqXHR) {
$.views.Roster.RosterViewModel.AddUsers(data);
},
OnError: function (jqXHR, status, errorThrown) {
var _response = $.parseJSON(jqXHR.responseText);
$.pnotify({ title:_response.title, text: _response.Message, type: _response.TypeString});
}
});
};
$.views.Roster.ViewModel = {
RosterUsers: ko.observableArray([]),
TotalRoster: null,
CurrentPage: ko.observable(1)
};
$.views.Roster.BindModel = function (data) {
var self = $.views.Roster.ViewModel;
$.views.Roster.ViewModel.TotalRoster = ko.computed(function () {
return self.RosterUsers().length;
});
$.views.Roster.RosterViewModel.AddUsers(data);
ko.applyBindings($.views.Roster.ViewModel);
}
Next = function () {
var _page = $.views.Roster.ViewModel.CurrentPage() + 1;
$.views.Roster.ViewModel.CurrentPage(_page);
$.views.Roster.GetPage(_page);
};
$.views.Roster.RosterViewModel = function (data) {
$.views.Roster.RosterViewModel.AddUsers(data);
};
$.views.Roster.RosterViewModel.AddUsers = function (data) {
$.each(data, function (index, value) {
$.views.Roster.RosterViewModel.PushUser(value);
});
};
$.views.Roster.RosterViewModel.PushUser = function (user) {
$.views.Roster.ViewModel.RosterUsers.push(new $.views.Roster.UserViewModel(user));
};
When you say 'once all the data has been loaded', I assume you mean when the GetPage method finishes loading a single page of users, as that is the only data loading that I see in the code above. Here is one way you can do it:
First, create an observable somewhere that you can bind to to tell the user if data is loading
$.views.Roster.ViewModel = {
RosterUsers: ko.observableArray([]),
TotalRoster: null,
CurrentPage: ko.observable(1),
DataIsLoading: ko.observable(false)
};
And add some markup that shows something in the UI when data is loading
<div data-bind="visible:DataIsLoading">Data is Loading, please wait...</div>
Then set DataIsLoading before you make the ajax call, then reset it when the call is done
$.views.Roster.GetPage = function ( pageNumber) {
$.views.Roster.ViewModel.DataIsLoading(true); // Add this!
$.grain.Ajax.Get({
Url: Views.Roster.Properties.Url,
DataToSubmit: { pageNumber: pageNumber, id: Views.Roster.Properties.Id },
DataType: "json",
OnSuccess: function (data, status, jqXHR) {
$.views.Roster.RosterViewModel.AddUsers(data);
$.views.Roster.ViewModel.DataIsLoading(false); // Add this!
},
OnError: function (jqXHR, status, errorThrown) {
var _response = $.parseJSON(jqXHR.responseText);
$.pnotify({ title:_response.title, text: _response.Message, type: _response.TypeString});
$.views.Roster.ViewModel.DataIsLoading(false); // Add this!
}
});
};

Fail to call a Json web service inside my asp.net mvc 4 application

I want to call the following webservice as mentioend on this link http://dev.joget.org/community/display/KB/JSON+API#JSONAPI-web%2Fjson%2Fworkflow%2Fprocess%2Flist
So inside my asp.net mvc view i wrote the folloiwng:-
<script type="text/javascript">
$(document).ready(function () {
// Send an AJAX request
$.getJSON("http://localhost:8080/jw/web/json/workflow/process/list?j_username=kermit&hash=9449B5ABCFA9AFDA36B801351ED3DF66&loginAs=admin",
function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, val) {
// Format the text to display.
var str = val.id + ': $' + val.packageName;
// Add a list item for the product.
$('<li/>', { text: str })
.appendTo($('#products'));
});
});
});
</script>
<h1>The Processes are</h1>
<ul id="products"/>
But when i run the above web page no processes will be displayed under the <h1>The Processes are </h1> , while if i type the following http://localhost:8080/jw/web/json/workflow/process/list?j_username=kermit&hash=9449B5ABCFA9AFDA36B801351ED3DF66&loginAs=admin directly on the address-bar of my browser then all the processes will be displayed. so what might be going wrong ?
BR
-::::UPDATED::::-
i HAVE UPDATED MY JAVASCRIPT TO BE AS FOLLOW:-
$(document).ready(function(){
$.ajax({
type: "GET",
url: "http://localhost:8080/jw/web/json/workflow/package/list?loginAs=admin",
dataType: "JSONP",
contentType: "application/json; charset=utf-8",
success: function (data) {
$.each(data, function (key, val) {
// Format the text to display.
var str = val.packageId + ': $ ' + val.packageName;
// Add a list item for the product.
$('<li/>', { text: str })
.appendTo($('#products'));
});
}});
});
but the result of the web service call is returned as
undefined: $ undefined
instead of being something such as:-
{"activityId":"","processId":"289_process1"}
So what is the problem that is preventing my code from displaying the right data ?
Try specifying the JSONP callback parameter as callback=? at the end of your query string as explained in the documentation:
var url = 'http://localhost:8080/jw/web/json/workflow/process/list?j_username=kermit&hash=9449B5ABCFA9AFDA36B801351ED3DF66&loginAs=admin&callback=?';
$.getJSON(url, function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, val) {
// Format the text to display.
var str = val.id + ': $' + val.packageName;
// Add a list item for the product.
$('<li/>', { text: str }).appendTo('#products');
});
});
UPDATE:
After showing your JSON (at last) the list of products is contained within a data property, so you need to adapt your $.each and operate on this property and not directly on the result:
{
"data": [
{
"packageName": "CRM",
"packageI‌​d": "crm"
},
{
"packageName": "EngineersAssociation",
"packageId": "EngineersAssociation"
},
{
"packageName": "LeaveApp",
"packageId": "leaveApp"
},
{
"packageName": "Newtest",
"packageId": "Newtest"
},
{
"p‌​ackageName": "TestApp",
"packageId": "testapp"
},
{
"packageName": "test54",
"packageId": "test5"
}
]
}
So adapt your code:
var url = 'http://localhost:8080/jw/web/json/workflow/process/list?j_username=kermit&hash=9449B5ABCFA9AFDA36B801351ED3DF66&loginAs=admin&callback=?';
$.getJSON(url, function (result) {
// On success, 'result.data' contains a list of products.
$.each(result.data, function (key, val) {
// Format the text to display.
var str = val.id + ': $' + val.packageName;
// Add a list item for the product.
$('<li/>', { text: str }).appendTo('#products');
});
});

Resources