How to bind Telerik MVC grid to DropDownList via Ajax? - model-view-controller

I am trying to bind a dropdownlist to a telerik grid, so that when the value of the dropdownlist changes the grid will update via ajax to show results. Here is my code so far:
IndexView:
<% Html.RenderPartial("AptProfileFilter"); %>
<%= Html.Telerik().Grid(Model.profiles)//Initial Server Binding
.Name("Profiles").DataBinding(dataBinding => dataBinding
.Ajax()
.Update("_AjaxBinding", "AptProfile", new {id = (string)ViewData["BuildingID"]}))
.Columns(columns =>
{
columns.Bound(p => p.AptProfileID).Width(100);
columns.Bound(p => p.Apartment.Building.Complex.Name).Width(100);
columns.Bound(p => p.Apartment.Building.BuildingID).Width(100);
columns.Bound(p => p.Apartment.AptRate).Width(100);
})
.Pageable()
.Sortable()
I used FireBug to determine that the correct data is being posted( after selecting a element from my dropdownlist)
back to the Data collection in the GridModel class, but I do not understand why it is not updating the Grid with this new data?
I am very new to web development. Thanks for your help!

I've been wrestling with this too. take a look at the link below (bottom of comment), in which I asked the same type of question. In my case, I managed to get this working, but still have some questions about HOW I got it working. Anyway, I hope this helps ... Also, in my case, I'm using Razor views, which you might not be, based upon you use of the <% operators ... Telerik MVC Grid: How to use DropDownList in a column?

Related

Kendo UI Grid returns JSON to browser (using MVC)

I've recently purchased a Kendo subscription, I'm having trouble getting an AJAX bound grid to operate as expected, hoping someone here can help.
I have followed the Kendo docs tutorial # http://docs.kendoui.com/getting-started/using-kendo-with/aspnet-mvc/helpers/grid/ajax-binding
and could get the AJAX binding working nicely.
I've tried to now implement it into an existing MVC solution, and whenever I click the New or Edit command button, I get a string of JSON returned to the browser. Similiar to issue (JSON data to KENDO UI Grid ASP.NET MVC 4) But the answer in that problem didn't work for me.
Here is my Controller code...
public ActionResult Index()
{
// non-important code removed here //
var viewModel = newReferenceViewModel();
ViewBag.TradeReferences = TradeReferenceWorker.Get(applicationId);
return View(viewModel);
}
public ActionResult TradeReferences_Read([DataSourceRequest]DataSourceRequest request)
{
var applicationId = GetCurrentApplicationId();
DataSourceResult result = TradeReferenceWorker.Get(applicationId).ToDataSourceResult(request);
return Json(result, "text/x-json", JsonRequestBehavior.AllowGet);
}
And the View ....
#(Html.Kendo().Grid((IEnumerable<TradeReference>)ViewBag.TradeReferences)
.Name("gridTradeReference")
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
model.Id(tradeReference => tradeReference.TradeReferenceId);
model.Field(tradeReference => tradeReference.TradeReferenceId).Editable(false);
})
.Read(read => read.Action("TradeReferences_Read", "References"))
.Create(create => create.Action("TradeReference_Create", "References"))
.Update(update => update.Action("TradeReference_Update", "References"))
.Destroy(destroy => destroy.Action("TradeReference_Destroy", "References"))
)
.Columns(columns =>
{
columns.Bound(tref => tref.TradeReferenceId).Visible(false);
columns.Bound(tref => tref.Name);
columns.Bound(tref => tref.Phone);
columns.Command(commands =>
{
commands.Edit();
commands.Destroy();
}).Title("").Width(200);
})
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable.Mode(GridEditMode.InLine))
.Sortable()
)
So to sum up... the Grid will load perfectly the first time. I haven't wired up anything on the Edit / Delete actions, just trying to get Create operational. Clicking Add New, or even Edit for that matter will make the browser simply display Json to the screen.
It is hopefully something simple - thanks in advance
Solved it - the problem was the kendo js files were not being referenced correctly.
In my particular case, the bundling wasn't done 100% correctly so the Kendo javascript files were never getting included in the page.
They must also appear in a certain order, as described in the troubleshooting guide http://docs.kendoui.com/getting-started/using-kendo-with/aspnet-mvc/helpers/grid/troubleshooting

kendo grid to excel

I'm tryin to export kendo grid to excel: i tried this method:
http://jsfiddle.net/SZBrt/4/
But i have a kendo grid already that gets data on button click.
I want another button to excel the grid with datas on export button click as mentioned in jsfiddle.
#(Html.Kendo().Grid<KendoGridExportExcelMvc.Models.Sales>()
.Name("Sale")
.Columns(columns =>
{
columns.Bound(p => p.R).Width(100);
columns.Bound(p => p.Cur).Width(100);
columns.Bound(p => p.goods).Width(100);
columns.Bound(p => p.cost).Width(70);
columns.Bound(p => p.isdeleted).Width(60);
})
.Sortable()
.Scrollable()
.HtmlAttributes(new { #style = "Font:12px calibri; " })
.Filterable()
)
how to bring this inside the js file. please help,
Well, dude, you are just rendering HTML.
If you want to generate a real CSV file, just use one of the classes from the System.IO namespace, and write directly to the Response's OutputStream.
See this article for reference on how to do it:
Writing to Output Stream from Action

Telerik grid shows an empty column after delete command

I am using Telerik MVC Extensions Grid control, with AJAX binding, and run a delete command. Deletion works as intended, and the grid updates so that it doesn't show the deleted row.
However, after deleting one of the grid columns (the first one) shows up empty. There is also difference in the second column - 'false' instead of the unchecked box.
Any ideas why, and how do I fix that?
I can refresh the screen, and that fixes the view. But it is a heavy page, and I'd rather not do the second refresh.
After deleting, the first column shows up empty:
My grid:
Html.Telerik()
.Grid(Model)
.Name("scenarioGrid")
.DataBinding(dataBinding => dataBinding.Ajax()
.Delete("Delete", "Scenario"))
.DataKeys(keys => keys.Add(c => c.Id))
.Columns(columns =>
{
columns.Template(o => Html.ActionLink(o.Name, "Index", new {id = o.Name})).Title("Scenario")
.FooterTemplate(#<text>Total #Model.Count() </text>);
columns.Bound(o => o.IsLocked);
columns.Bound(o => o.ContractMonth);
columns.Bound(o => o.CreateDate);
columns.Command(commands => commands.Delete().ButtonType(GridButtonType.Image)).Title("Delete");
}
)
.Sortable()
.Scrollable(scroll => scroll.Height(200))
.ClientEvents(events => events.OnDelete("onDelete").OnComplete("afterDelete"))
You shouldn't use columns.Template with Ajax binding. It's meant for server side bound grids. You should use
columns.Bound(o => 0.whatever).ClientTemplate("convert your link to a string here");
It looks like you are using server binding to load the grid, but ajax binding to update it. columns.Template is used for server binding. You should use ClientTemplate for ajax binding.

Telerik Extensions for MVC grid OnRowSelect problem

I have a Telerik Extensions for ASP .Net MVC grid on my web page and, even though I've added the "Selectable" method to it, the OnRowSelect event is not getting triggered. It seems that the grid is not even responding to the "Selectable" method since my mouse pointer does not change to the hand when I'm hovering over the grid.
Here is the grid declaration:
<% Html.Telerik().Grid(Model.Students)
.Name("Students")
.DataKeys(keys =>
keys.Add(s => s.Id)
)
.Columns(columns =>
{
columns.Bound(s => s.CourseScore).ReadOnly();
columns.Bound(s => s.StudentName).ReadOnly();
columns.Bound(s => s.Points).ReadOnly();
columns.Template(s =>
{%>
<input name="GradeReleaseStatus" type="checkbox" value="<%=s.GradeRelease%>"
<%if (s.GradeRelease)
{%>
checked="checked"
<%}%>
/>
<%
}).Title("Release Grade");
})
.Selectable()
.ClientEvents(events => events.OnRowSelect("Activities.DisplaySingleGrade"))
.Render(); %>
Can anyone tell me what I'm missing or doing wrong?
Thanks.
Do you see a hover effect when you move the mouse over a grid row? If yes - then selection is working. If not - probably there is a JavaScript error in your page. If you don't see a JavaScript error make sure the grid initialization JavaScript is output. This needs a ScriptRegistrar component to be present after the grid declaration. Lastly you can try with a simpler script to see if the JavaScript event is raised:
events.OnSelect("onSelect")
<script>
function onSelect() {
alert("OnSelect");
}
</script>

Telerik RadGrid CustomSorting without hitting database?

I tried to post on Telerik forum, but now each time I try to open my thread, I get
"Oops...
It seems there was a problem with our server."
So I posted this question here.
I am pretty new to Telerik and RadGrid. I am trying to modify existing project because client needs custom sorting. There is a data field which may contain numbers or text so it is a string type but sometimes it has to be sorted as numbers. So I went to this link:
http://demos.telerik.com/aspnet-ajax/grid/examples/programming/sort/defaultcs.aspx
and
http://www.telerik.com/help/aspnet-ajax/grdapplycustomsortcriteria.html
The example says:
"With custom sorting turned on, RadGrid will display the sorting icons but it will not actually sort the data."
but it seems it is not enough to add AllowCustomSorting to disable default sorting.
When implementing SortCommand, I noticed that I have to do
e.Canceled = true;
because else default sorting occurs. Why this is not mentioned in the documentation nor example?
But the main question is - inside of SortCommand my RadGrid already has all items loaded. So is there any way to sort them to avoid hitting database? I tried accessing various Items properties of both "object source, GridSortCommandEventArgs e", but all Items are read-only, so I cannot sort them and attach back to the RadGrid.
Thanks for any ideas.
You can set the sortExpression in the OnSelecting event of the objectDatasource and use it in the SelectMethod.
protected void odsGridData_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
e.InputParameters["filterExpression"] = grdMyTasks.MasterTableView.FilterExpression;
//Set the Sort Expression and use this in the Get method
e.InputParameters["sortExpression"] = grdMyTasks.MasterTableView.SortExpressions.GetSortString();
e.Arguments.StartRowIndex = grdMyTasks.CurrentPageIndex;
e.Arguments.MaximumRows = grdMyTasks.PageSize;
}
This way you can perform custom sort and pass on the data to the RadGrid.
Hope this helps.
Here is an example of some code I use that does not hit the database. I'm using MVC 3 with the Razor view engine. Notice the Ajax binding. Don't forget to add using Telerik.Web.Mvc.UI and annotate the "Post" methods in your controller with [GridResult] and to return GridModel to get the Json resultset.
using Telerik.Web.Mvc;
[GridAction]
public ActionResult AjaxGridSelect()
{
return View(new GridModel(db.lm_m_category));
}
Here is the index.cshtml (razor engine), the key is the Ajax binding.
#model IEnumerable<LinkManagerAdmin.Dal.lm_r_category>
#using Telerik.Web.Mvc.UI
#(Html.Telerik().Grid(Model)
.Name("Grid")
.DataKeys(keys => keys.Add(c => c.category_id ))
.DataBinding(dataBinding => dataBinding.Ajax()
.Select("AjaxGridSelect", "CategoryTree")
.Insert("GridInsert", "CategoryTree", new { GridEditMode.PopUp, GridButtonType.ImageAndText })
.Update("GridUpdate", "CategoryTree", new { GridEditMode.InLine, GridButtonType.ImageAndText })
.Delete("GridDelete", "CategoryTree", new { GridEditMode.InLine, GridButtonType.ImageAndText }))
.Columns(columns =>
{
columns.Bound(p => p.category_name).Width(150);
columns.Bound(p => p.status_cd).Width(100);
columns.Command(commands =>
{
commands.Edit().ButtonType(GridButtonType.ImageAndText);
commands.Delete().ButtonType(GridButtonType.ImageAndText);
}).Width(180).Title("Commands");
})
.Editable(editing => editing.Mode(GridEditMode.InLine))
.Pageable(paging => paging.PageSize(50)
.Style(GridPagerStyles.NextPreviousAndNumeric)
.Position(GridPagerPosition.Bottom))
.Sortable(o => o.OrderBy(sortcol =>
{
sortcol.Add(a => a.category_name);
sortcol.Add(a => a.add_date);
})
.Filterable()
.Groupable()
.Selectable())

Resources