I have a kendo grid that has checkboxes for selection.
When I click a checkbox, I change the class of the row to "k-state-selected" and save the row id in
var checkedIds = [];
I then have a context menu where I can select the change I want to apply to the row.
In this case, I want to change the value Something of all rows. That works.
Then, I have this piece of code that restores the previous selected rows.
private setCheckRows(checkedIds) {
$.each(checkedIds, (index, value) => {
$("#grid tbody").find("tr").each(
function () {
if ($(this).closest("tr").attr("Id") === value) {
$(this).closest("tr").addClass("k-state-selected")
.attr("style", "background-color: rgb(51,121,181)")
.find(".checkbox")
.attr("checked", "checked");
}
});
});
}
It works, but then again it doesn't...
If I select one checkbox, this bit of code does nothing
if ($(this).closest("tr").attr("Id").replace("task-row-", "") === value) {
$(this).closest("tr").addClass("k-state-selected")
.attr("style", "background-color: rgb(51,121,181)")
.find(".checkbox")
.attr("checked", "checked");
}
If I select two or more checkboxes, it works on all rows except the first.
So all rows, except the first one, are restored to being selected and with a blue background.
This is indeed a very strange behaviour.
Any ideas?
Tks in advance.
I managed to solve it.
I changed this
$.ajax({
type: "POST",
url: "/Cockpit/SetWorkflowStep",
dataType: "json",
data: JSON.stringify(newTaskStatus),
contentType: "application/json"
}).done(() => {
$("#grid").data("kendoGrid").dataSource.read();
this.setCheckRows(checkedIds);
});
into this
$.ajax({
type: "POST",
url: "/Cockpit/SetWorkflowStep",
dataType: "json",
data: JSON.stringify(newTaskStatus),
contentType: "application/json"
}).done(() => {
$("#grid").data("kendoGrid")
.dataSource.read()
.done(() => { this.setCheckRows(checkedIds); });
});
Now it works fine.
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)
}
});
});
});
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!
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
Problem: Check box value display null in controller.cs. but it is working perfectly according to selection of row from jqgrid. But when I select any row and update all the field it will pass to the controller with modified value but only IsEnabled field comes null.
I have Database Field called IsEnabled which has Bit data type.
I have written following code in .cshtml
<input type="checkbox" value='Yes' offval='No' name="IsEnabled" />
I am using following code to bind check box value as per in database
grid.jqGrid('GridToForm', gsr, "#order");
I have save button. When I click on save following code will execute
$("#btnSave").click(function () {
var data = JSON.stringify($('#order').serializeObject());
var href = '#Url.Action("SaveData", "Users")';
var ajaxResponse = $.ajax({
type: "post",
url: href,
dataType: 'json',
data: data,
contentType: "application/json; charset=utf-8",
success: function (result) {
if (result.Success == true) {
alert("Success");
}
else {
alert("Error: " + result.Message);
}
}
});
Following code written in Controller.cs
(in FormValue it will show all the updated value correctly except IsEnabled, it will display always null.)
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SaveData(User FormValue)
{
string message = "";
return Content(message);
}
You must delete this code ( if use jquery ajax )
[AcceptVerbs(HttpVerbs.Post)]
when you use post back and send class use above code
send class with jQuery use this code:
try it:
$.ajax({
type: "post",
url: href,
dataType: 'json',
data: SON.stringify({ FormValue : { ID : $('#controlIdName').val() , Name : $('#ControlName').val() } }),
contentType: "application/json; charset=utf-8",
success: function (result) {
if (result.Success == true) {
alert("Success");
}
else {
alert("Error: " + result.Message);
}
}
I am using Mvc3 and my view engine is razor and also writing jquery in my view,
how can i assign a value to text box based on select a value from drop down list.
example:
if i am selected EmpId form drop down then the text box will be fill with Employee Name form same table.
$("#Emplist").change(function(){
$.ajax({
url:"#Url.Action("GetEmployeeName","Employee")",
data:{
id: $(this).val()
},
success: function(data){
$("#EmployeeName").val(data);
}
})
})
<select id="Emplist"><option value='1'>Mehmet</option></select>
public string GetEmployeeName(int id){
var emp = //Get Employee by Id
return emp.Name
}
You could bind your OnChange event, make an ajax call and then populate the textbox with the response. You can pass a json result as response, and handle all the parameters you want.
$('#dropDownId').change(function()
{
empId = $(this).attr('value');
$.ajax({
url: '#Url.Action("Action", "Controller")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ EmpId: empId }),
success: function (data) {
if (data.Result) {
$("#txtId").val(data.EmpName);
}
}
});
});
Here is a sample example, where dropDownBoxId is the id of the dropDownBox and txtBoxId is the id of Textbox.
$(function () {
$('#dropdownBoxId').change(function () {
// gets the value from the drop down box
var selected = $("#dropdownBoxId option:selected").text();
// puts the value into the textbox
var txtBox = document.getElementById('txtBoxId');
txtBox .value = selected
});
});