html part
<input data-bind="kendoComboBox: { dataTextField: 'FirstName', dataValueField: 'PersonID', data: AllUsers,template: '<span>#= data.FirstName # #= data.LastName # </span>', value: SelectedUserID,
change: UserSelectionChanged}" />
event handler inside model
var self= this;...
self.UserSelectionChanged = function () {
$.ajax({
type: "POST",
url: defaultUri + '/Home/GetUserTasks',
data: JSON.stringify({ PersonID: self.SelectedUserID() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (o) {
self.SelectedUserTask(null);
self.SelectedUserTask(o);
//RRM: Added this line below so that whenever user dropdown is changed or refresh button is clicked in AssignedTo the first task of that particular user is Selected.
self.selectTask(o[0]);
}
});
};
here the event is being called but the data in self is not there. The event doesn't seems to be bind well with knockout.
how to properly bind the ko event in the kendo combobox event?
Instead of registring to the change event, I'd subscribe to SelectedUserID:
var self= this;
...
self.SelectedUserID.subscribe(function(selectedUserId) {
$.ajax({
type: "POST",
url: defaultUri + '/Home/GetUserTasks',
data: JSON.stringify({ PersonID: selectedUserId }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (o) {
self.SelectedUserTask(null);
self.SelectedUserTask(o);
//RRM: Added this line below so that whenever user dropdown is changed or refresh button is clicked in AssignedTo the first task of that particular user is Selected.
self.selectTask(o[0]);
}
});
});
This way it doesn't matter when or how the SelectedUserID is being changed.
As sroes wrote subscribing to the observable is the best choice here.
In cases where you have to bind to the kendo event then you can do this:
data-bind="... change: UserSelectionChanged(), ...."
Notice the function call parenthesis at the end ^
Now you function has to be like this:
this.UserSelectionChanged = function () {
var self = this;
return function(e) {
$.ajax({
self.blah ...
});
}
}
Now you have created a closure and you can access your view model using self but you also have the original Telerik event args inside e like e.dataItem etc.
So now you are unstoppable, you can do everything!
Related
I have a PartialView which renders a Grid using a List of Model Class passed from the controller.
#model IEnumerable<DeliveryDashboard.Models.UpcomingDMR>
#Html.Partial("~/Views/Shared/_DMRGrid.cshtml", Model)
The Grid Renders perfectly. Now I have added a Drop down at the top of the Grid.
in the OnChange event of the Drop down, I need to hit the controller and get an Updated list of Same Model Class which should refresh the existing Grid.
<script type="text/javascript">
$(function () {
//Refresh Grid on Date Range Change
$('#DateRange').change(function () {
$.ajax({
url: '#Url.Content("~/DMR/UpcomingDMRByDateRange/")',
dataType: 'json',
type: 'POST',
data: JSON.stringify({ DateRange: $('#DateRange option:selected').val() }),
contentType: 'application/json',
success: function (result) {
// Refresh partialView Here
}
});
});
});
My controller code returns the List of Model Class which I need to use to bind the Partial View.
public List<UpcomingDMR> UpcomingDMRByDateRange(string DateRange)
{
// get data from database and prepare List<UpcomingDMR>
return NewDataList;
}
Now How can I refresh my partial View from the Success block of my Ajax Call ?
You can do it like this in your success method :
$(function () {
//Refresh Grid on Date Range Change
$('#DateRange').change(function () {
$.ajax({
url: '#Url.Content("~/DMR/UpcomingDMRByDateRange/")',
dataType: 'json',
type: 'POST',
data: JSON.stringify({ DateRange: $('#DateRange option:selected').val() }),
contentType: 'application/json',
success: function (result) {
$("#your_partial_view_id").load('#Url.Action("Foo","Bar")',result)
}
});
});
});
I have a bootstrap modal which holds a form and from holds a select option field and I would like to populate this with help of ajax on modal('show')
So I have been trying the following but on first click won't fire and after each click the request are duplicated
$('#addNew').modal('show');
$('#addNew').on('show.bs.modal', function(e) {
//ajax call to populate select option
var url = ajaxurl + '?action=getCategories';
$.ajax({
type: "POST",
cache: false,
success: function(html) {
}
});
});
Why not changing the scenario?
function showAddNewModal(){
//ajax call to populate select option
var url = ajaxurl + '?action=getCategories';
$.ajax({
type: "POST",
cache: false,
success: function(html) {
//populate select option here
$('#addNew').modal('show');
}
});
}
Also when you are using POST method , you should change your request to :
$.ajax({
url:ajaxurl,
data:{"action":"getCategories"},
type: "POST",
cache: false,
success: function(html) {
//populate select option here
$('#addNew').modal('show');
}
});
I have created Accrodions dynamically and inside each pane is a link button. I have assigned a value to the ID of the link button. what I want to accomplish is that when I click on a link button in one of my pane I want to use the ID' value as the parameter.
My Ajax:
function FireThisEvent() {
var Value;
$("lnkCopy").click(function(event) {Value = (event.target.id);})
alert(Value);
alert(lnkCopy.val());
$.ajax({
type: "POST",
url: "frmSchemeSetup.aspx/sbGetData",
data: '{sdPreNo: Value}',
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "JSON",
timeout: 10000,
success: function() {
alert("YEAH!!!");
},
error: function(xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
}
How can I accomplish this?
This is where I add the event to my link button
lnkCopy.Attributes.Add("onclick", "FireThisEvent()")
I manage to get my Ajax to call my WebMethod with the help of this following post.
I have some strange behaviour going on with the jQuery ajax functionality in my asp.net MVC3 application.
I have several boxes of data each containing a link to open a popup and change the data in each box. To do this I've added a jquery live() click event to process the data via a jQuery ajax call. In the "success" method of the ajax call, i take the return data and open a UI Dialog popup (a partial view) which contains a list of radio buttons. I select a different radio button and press 'close' - the close button fires another live() click event, processes that new data via an ajax call which refreshes the data in the box on the main page.
This works perfectly first time. If you then click to change it again, the popup opens, allows you to select a new value, but this time pressing close on the popup triggers two click events which throws an null error in my MVC controller.
If you repeat this process it triggers 3 click events, so it's clear that live() is appending these events somewhere.
I've tried using on() and click(), but the page itself is made up of panels loaded in via ajax so I used live() to automatically bind the events.
Here is the code I'm using:
HTML
<p><!--Data to update goes here--></p>
Update Data
First Click event calling popup with Partial View
$('a.adjust').live('click', function (e) {
var jsonData = getJsonString(n[1]);
var url = '#Url.Action("ChangeOptions", "Search")';
var dialog = $('<div id="ModalDialog" style="display:none"></div>').appendTo('body');
// load the data via ajax
$.ajax({
url: url,
type: 'POST',
cache: false,
contentType: "application/json; charset=utf-8",
data: jsonData,
success: function (response) {
dialog.html(response);
dialog.dialog({
bgiframe: true,
modal: true
}
});
}
});
e.preventDefault();
});
Second click event the takes the new info to return updated partial view
$('a#close').live('click', function (event) {
var jsonData = getJsonString(n[1]);
var url = '#Url.Action("GetChangeInfo", "Search")';
$.ajax({
url: url,
type: 'POST',
contentType: "application/json; charset=utf-8",
data: jsonData,
success: function (response) {
$('#box-' + #column).html(response); //this refreshes the box on the main page
},
error: function () {
}
});
$('#ModalDialog').dialog('close');
event.preventDefault();
});
Anybody know what might be happening here, and how I could resolve it?
Use namespaces to unbind previous click binds like this:
$('a.adjust').unbind('click.adjustclick');
Then bind the click action to a.adjust:
$('a.adjust').bind('click.adjustclick', function(){
//your code here
//note the return false, this prevents the browser from visiting the URL in the href attribute
return false;
});
If i understand you correctly, you try to run the second click action when the dialog is closed. Therefor I would use the build in close function for the dialog like this:
$('a.adjust').bind('click.adjustclick', function(){
var jsonData = getJsonString(n[1]);
var url = '#Url.Action("ChangeOptions", "Search")';
var dialog = $('<div id="ModalDialog" style="display:none"></div>').appendTo('body');
// load the data via ajax
$.ajax({
url: url,
type: 'POST',
cache: false,
contentType: "application/json; charset=utf-8",
data: jsonData,
success: function (response) {
dialog.html(response);
dialog.dialog({
bgiframe: true,
modal: true,
close: function(){
var jsonData2 = getJsonString(n[1]);
var url2 = '#Url.Action("GetChangeInfo", "Search")';
$.ajax({
url: url2,
type: 'POST',
contentType: "application/json; charset=utf-8",
data: jsonData2,
success: function (response2) {
$('#box-' + #column).html(response2); //this refreshes the box on the main page
},
error: function () {
}
});
}
}
});
}
});
});
If you are using your own button a#close, bind a click event to it to close the dialog, it will automatically fire the close function for the dialog.
$('a#close').unbind('click.closedialog');
$('a#close').bind('click.closedialog', function () {
$('#ModalDialog').dialog('close');
return false;
}
Try this:
$('a#close').unbind('click').bind('click', function (event) {
//Your Code
});
I am using ASP.NET MVC3 with EF Code First. I have not worked previously with jQuery. I would like to add autocomplete capability to a dropdownlist that is bound to my model. The dropdownlist stores the ID, and displays the value.
So, how do I wire up the jQuery UI auto complete widget to display the value as the user is typing but store the ID?
I will need multiple auto complete dropdowns in one view too.
I saw this plugin: http://harvesthq.github.com/chosen/ but I am not sure I want to add more "stuff" to my project. Is there a way to do this with jQuery UI?
Update
I just posted a sample project showcasing the jQueryUI autocomplete on a textbox at GitHub
https://github.com/alfalfastrange/jQueryAutocompleteSample
I use it with regular MVC TextBox like
#Html.TextBoxFor(model => model.MainBranch, new {id = "SearchField", #class = "ui-widget TextField_220" })
Here's a clip of my Ajax call
It initially checks its internal cached for the item being searched for, if not found it fires off the Ajax request to my controller action to retrieve matching records
$("#SearchField").autocomplete({
source: function (request, response) {
var term = request.term;
if (term in entityCache) {
response(entityCache[term]);
return;
}
if (entitiesXhr != null) {
entitiesXhr.abort();
}
$.ajax({
url: actionUrl,
data: request,
type: "GET",
contentType: "application/json; charset=utf-8",
timeout: 10000,
dataType: "json",
success: function (data) {
entityCache[term] = term;
response($.map(data, function (item) {
return { label: item.SchoolName, value: item.EntityName, id: item.EntityID, code: item.EntityCode };
}));
}
});
},
minLength: 3,
select: function (event, result) {
var id = result.item.id;
var code = result.item.code;
getEntityXhr(id, code);
}
});
This isn't all the code but you should be able to see here how the cache is search, and then the Ajax call is made, and then what is done with the response. I have a select section so I can do something with the selected value
This is what I did FWIW.
$(document).ready(function () {
$('#CustomerByName').autocomplete(
{
source: function (request, response) {
$.ajax(
{
url: "/Cases/FindByName", type: "GET", dataType: "json",
data: { searchText: request.term, maxResults: 10 },
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
label: item.CustomerName,
value: item.CustomerName,
id: item.CustomerID
}
})
);
},
});
},
select: function (event, ui) {
$('#CustomerID').val(ui.item.id);
},
minLength: 1
});
});
Works great!
I have seen this issue many times. You can see some of my code that works this out at cascading dropdown loses select items after post
also this link maybe helpful - http://geekswithblogs.net/ranganh/archive/2011/06/14/cascading-dropdownlist-in-asp.net-mvc-3-using-jquery.aspx