How to bind a telerik mvc dropdown using javascript - telerik

I have an application with two telerik mvc drop-downs - region and country. I need to populate the country drop-down using an ASMX Web Service every time the region drop-down change. In other words I need to pass a parameter to the web service and a way to call the bind method form the client. This is what I have but it's not working.
#(Html.Telerik().DropDownList()
.Name("RegionDDL")
.BindTo(new SelectList(Model, "value", "value"))
.ClientEvents(events => events.OnChange("onChange"))
)
#(Html.Telerik().DropDownList()
.Name("SeasonDDL")
.ClientEvents(events => events
.OnDataBinding("onDropDownListDataBinding")
)
.DataBinding(dataBinding => dataBinding
.WebService().Select("~/country.svc/GetSeasonDropDownItems"))
)
Now the scripts
<script type="text/javascript">
var RegionDDLv;
function onChange() {
//Get the region
RegionDDLv = $("#RegionDDL").data("tDropDownList").value();
var countryDDLv = $("#countryDDL").data("tDropDownList");
countryDDLv.dataBind();//THIS IS NOT WORKING
}
function onDropDownListDataBinding(e) {
e.data = { region: RegionDDLv };
}
</script>
Thanks

After some research, I found the answerer here
http://www.telerik.com/help/aspnet-mvc/telerik-ui-components-combobox-client-api-and-events.html
It is
countryDDLv.reload();

try
SeasonDDLv.rebind();
instead of
SeasonDDLv.dataBind();

Related

Using a custom window with ajax form to add new grid row

I need to create a more advanced method of adding new elements to a kendo grid, so in short I have replicated the following example as it does exactly what I needed:
https://github.com/telerik/ui-for-aspnet-mvc-examples/tree/master/window/KendoWindow-Ajax-Form
And it works just fine. Only difference is the new row is added in it's correct spot in the grid, and not on the top as per usual. How can I, using the example linked to, place the new row on the top?
(I'm thinking it's not necessary to show my code here as it very closely resembles the code given in the link above)
So If you want to add a row up top I am thinking you could use a custom template. I may not be very clear on what you are doing but , I will attempt to help you.
Here is the grid in the code:`
#(Html.Kendo().Grid<OrderViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.Message).EditorTemplateName("MessageEditor");
}
.DataSource(datasource => datasource
.Ajax()
.Read(read => read.Action("GetOrders", "OrdersData"))
)
)`
Then write the template like this:
<script type="text/x-kendo-template" id="MessageEditor">
<div class="k-header k-grid-toolbar">
<div style="display: inline-block; font-size:1.25em; padding:
</div>
</div>
</script>
Well this may not be the best solution , however it is the only way I know to create a custom column in a Kendo grid
Ended up finding the solution myself eventually. Going by the example in the link I made in the original post, this is what I did:
Firstly when a new "order" is made, I make sure that the model returned in the "Create" method in OrdersDataController has an ID from when the model is added to the DB.
So when this part gets executed in "_OrdersCreate.cshtml":
#if (Model != null && ViewData.ModelState.IsValid)
{
<script>
closeCreatePopup();
</script>
}
I send information on the new Order created. So to that end I have modified "closeCreatePopup()" to handle arguments.
So for the finished results I will just use a piece of code from my own project, the following is my implementation of "closeCreatePopup()":
function closeCreateEmployeeWindow(name, rHPersonID, personID, organizationID) {
if (name !== undefined
&& rHPersonID !== undefined
&& personID !== undefined
&& organizationID !== undefined) {
var grid = $("#grid").data("kendoGrid");
grid.dataSource.insert({ Name: name, RHPersonID: rHPersonID, PersonID: personID, OrganizationID: organizationID });
grid.dataSource.sync();
}
var wnd = $("#createEmployeeModal").data("kendoWindow");
wnd.refresh({ url: '#Url.Action("CreateEmployee", "Employee", new { Area = "Administration" })' });
wnd.close();
}
The important part is this:
var grid = $("#grid").data("kendoGrid");
grid.dataSource.insert({ Name: name, RHPersonID: rHPersonID, PersonID: personID, OrganizationID: organizationID });
grid.dataSource.sync();
What is happening here is I use the "insert" method from the grid, and add a new object. "Insert" inserts the new object to the very top of the grid. Remember to call the "sync" method right after.
By doing it like this, the normal "create" method built into the grid is replicated.

Post kendo grid values

Below is the Kendo grid
#(Html.Kendo().Grid<CS.Web.Models.People.GroupDetailModel>()
.Name("Grid")
.Events(e => e.DataBound("LineItems_Databound"))
.HtmlAttributes(new { style = "overflow:hidden;", #class = "normalgrid" })
.Columns(columns =>
{
columns.Bound(p => p.GroupID).Hidden();
columns.Bound(p => p.GroupName).Title("Group Name").Width(30);
columns.Bound(p => p.Department).Title("Department Name").Width(30);
columns.Bound(p => p.IsBlindSettingsEnable).Title("Blind Group")
.ClientTemplate("<input type=\"checkbox\" #= IsBlindSettingsEnable ? \"checked=checked\": \"\" # enabled=\"enabled\" />")
.Width(30);
columns.Bound("Department").Title("Remove")
.ClientTemplate("<a href='javascript:void(0)' Title='Remove' onclick='return removeUserGroupRelation(+#=GroupID#+);'> <img alt='Remove' src='" + #Url.Content("~/Content/Images/delete_icon.png") + "' /></a>")
.Width(30);
})
.Sortable()
.Scrollable(scrollable => scrollable.Virtual(false))
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("getAssignedGroups", "People")
.Data("setRoutesValues")
)
//new { MerchantId = ViewBag.MerchantId, StartDate = Model.StartDate, EndDate = Model.EndDate }
)
.TableHtmlAttributes(new { #class = "grid_1" })
)
Below is the javascript code
var userID = '#ViewBag.UserID'
$.ajax({
url: '#Url.Action("SaveGroupsUserDetails")',
type: "POST",
dataType: "json",
data: { models: kendo.stringify($("#Grid").data("kendoGrid").dataSource.view()), UserID: userID },
success: function (result) {
}
});
Here in my kendo grid there is checkbox column.When i check or uncheck checkbox at CLIENT sied(in browser).And Do post via give javascript $.ajax post,it will not post the values of checkboxes which I have changed on client browser,it shows the values which it was binded from server side.
so,my question is to I want updated values to post on server which are modified on client browser.
I shall be very thankfull if you provide me answer.
You should just update your datasource on checkbox checked :
...
.ClientTemplate("<input type=\"checkbox\" #= IsBlindSettingsEnable ? \"checked=checked\": \"\" # enabled=\"enabled\" onclick='setChecked(this)' />")
...
function setChecked(cb) {
var row = $(cb).closest("tr");
var item = grid.dataItem(row);
item.IsBlindSettingsEnable = cb.checked;
}
and now your datasource is synced with the view
I believe this is because your looking at the actual value of the dataSource and not the grid itself. Your grid is non-editable. You are manually throwing the inputs into your grid and these will not effect the dataSource.
You can take two approaches do this kind of update.
You can leave the grid the way you have it set up and handle this update solely though Java Script.
To do this you will need to look up all the dataItems you need to update manually with JQuery.
You can lookup all of your check boxes with in that grid that are check, then get the relevant dataItem manually. Here is a short example showing how to get a dataItem from a row in the grid.
//checkbox is a JQuery object referencing one of your checkboxes
var row = $(checkbox).closest("tr");
var grid = $("#grid").data("kendoGrid");
var data = grid.dataItem(row);
Once you have all of your dataItems that are relevant you can then post your update. You would then have to reload your grid to get the updated status of these items.
Overall this is not the preferred way to do this kind of update with a kendo grid.
I suggest this second method.
This is the site where I will be pulling examples from: http://demos.telerik.com/aspnet-mvc/grid/editing
First you will need to make your kendo grid editable .Editable(editable => editable.Mode(GridEditMode.InCell)). You will not need the custom template that adds the checkbox anymore. It will automatically add them when you are editing your grid now.
You will need to then set the datasource to have an update function and have your server expect this update.
Your dataSource binding
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.Read("Editing_Read", "Grid")
.Update("Editing_Update", "Grid")
)
And your server side code
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Editing_Update([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<ProductViewModel> products)
{
if (products != null && ModelState.IsValid)
{
foreach (var product in products)
{
productService.Update(product);
}
}
return Json(products.ToDataSourceResult(request, ModelState));
}
By returning this Json object your grid will auto update to the new values. This is the preferred way to edit a grid.

From Telerik to Kendo Treeview ItemDataBound

I am currently changing a website, where the company wants to change everything from Telerik to Kendo.
And I have now run into some troubles. In the BindTo method can have some mappings, and .ItemDataBound. And in that, you can set a Value. A full example is here:
#(Html.Kendo().TreeView()
.Name("MenuTree")
.Checkboxes(true)
.ExpandAll(true)
.DragAndDrop(false)
.Events(events => events.Select("onChecked"))
.BindTo(enumNames, mappings =>
{
mappings.For<string>(binding => binding.ItemDataBound((item, menuGroup) =>
{
item.Text = this.GlobalResource("EnergyLine", menuGroup);
MenuGroup result;
Enum.TryParse(menuGroup, true, out result);
item.Value = ((int)result).ToString(CultureInfo.InvariantCulture);
....
But Kendo does not have the attribute Value. What is the corresponding attribute for Kendo?
Try item.Id instead of item.Value.

Telerik ASP.NET MVC 3 Grid - setting row background

I'm using Telerik Grid. I need to set background color for the entire row based on some property in view model. I've tried to do it as below by setting a background in IF statement for each column but backgound applies only on element not all cell (td). Also it seems it's a very "dirty" way to accomplish this task.
#(Html.Telerik().Grid(Model.SomeItems).Name("Grid")
.Columns(columns =>
{
columns.Template(
#<text>
#if (Model.IsOfSpecialColor)
{
<div class="gridRowBackground">
#Html.ActionLink(...)
</div>
}
else
{
#Html.ActionLink(...)
}
</text>).Title("Blabla");
});
You can change it using onRowDataBound event
#(Html.Telerik().Grid<Customer>()
.Name("Grid2")
.DataBinding(d => d.Ajax().Select("Select", "Home"))
.ClientEvents(e => e.OnRowDataBound("onRowDataBound"))
)
and the function is
<script>
function onRowDataBound(e) {
if (e.dataItem.ID == 2) {
e.row.style.backgroundColor = "grey";
}
}
</script>
If you are using server data binding, you can use CellAction. However, if you are using ajax data binding, you will need to use a solution like Tassadaque suggests.
#(Html.Telerik().Grid(Model.SomeItems)
.Name("Grid")
.CellAction(cell =>
{
if (cell.DataItem.IsOfSpecialColor.Value)
{
cell.HtmlAttributes["style"] = "background-color: red";
}
})

Custom Button in a ClientRowTemplate on the Telerik MVC Grid

Sorry if this is a repeat. I did a search and didn't find anything that exactly matched my situation.
I have a grid that requires a ClientRowTemplate. I have the template working very well.
I need a button in that RowTemplate that calls back to a controller method through ajax. The controller method needs to perform some complex logic and then return a new set of data to the grid which the grid will then need to bind to. I thought this should work in the same fashion as an ajax binding. For instance, when you do a save or delete (using the built in buttons) an ajax method that is attributed with [GridAction] is called and then has an IQueryable returned. The grid automatically binds to this IQueryable.
How do I do the same thing with a custom button? Is it even possible to add a custom button when using a ClientRowTemplate?
Put a link in the clienttemplate of your grid row
#(Html.Telerik().Grid<myModel>()
.Name("myGrid")
.Columns(columns =>
{
#* You can put a link in your client template to trigger a refresh function *#
columns.Bound(o => o.Id).ClientTemplate("<a href='javascript:refreshGrid(<#= Id #>);'>Refresh</a>");
columns.Bound(e => e.col1);
columns.Bound(e => e.col2);
columns.Bound(e => e.col3);
})
.ClientEvents(events => events.OnDataBinding("myGrid_onRowDataBinding"))
.DataBinding(dataBinding => dataBinding.Ajax().Select("Action", "Controller", new { param1 = ..., param2 = ... } )))
Write your code to refresh grid
<script type="text/javascript">
//parameters needed for grid
var x = ...;
var y = ...;
//grid refresh function
function refreshGrid(id) {
//make a call to server
$.post("/controller/action/" + id, function() {
//after making a successfull call to server
//you may update parameters
x = ...;
y = ...;
//and rebind your grid
$('#myGrid').data('tGrid').rebind();
})
}
//grid on row data binding event
function myGrid_onRowDataBinding(e) {
e.data = $.extend(e.data, { param1: x, param2: y });
}
</script>
That's it
EDIT:
ClientRowTemplate example
You need to change only the grid code. The rest is same.
#(Html.Telerik().Grid<myModel>()
.Name("myGrid")
.ClientRowTemplate(grid => "<div class='firstcolumn'><a href='javascript:refreshGrid(<#= Id #>);'>Refresh</a></div><div class='secondcolumn'>Content....</div>")
.ClientEvents(events => events.OnDataBinding("myGrid_onRowDataBinding"))
.DataBinding(dataBinding => dataBinding.Ajax().Select("Action", "Controller", new { param1 = ..., param2 = ... } )))

Resources