Telerik MVC export to excel - asp.net-mvc-3

I was using Telerik Grid in MVC3 project. In this I have to use the functionality of exporting. In order to export data, I need all the currently available items should be exported as excel format.
I done with exporting. But I need to export all the data currently are available in the grid. It means when filtering Not only the current page's data, It should export all the filtered data's.
I have done something like this: But its not exporting only the filtered data's but all the data's in the grid.
View Code
#(Html.Telerik().Grid(Model)
.Name("Grid")
.ToolBar(commands => commands
.Custom()
.HtmlAttributes(new { id = "export" })
.Text("Export to Excel")
.Action("ExportExcel", "Grid",
new { page = 1, orderBy = "~", filter = "~" }))
.DataKeys(keys =>
{
keys.Add(Id => Id.Itemid);
})
Action Method in my Controller
public ActionResult ExportExcel(int page, string orderBy, string filter)
{
IEnumerable orders = GetItems()
.AsQueryable()
.ToGridModel(page, int.MaxValue, orderBy,
string.Empty, filter).Data;
Is there any way that I can do with this. Please help for this.
Thanks,

The following example shows how to export only the relevant data: http://demos.telerik.com/aspnet-mvc/grid/customcommand
There is also a code library project which shows how to export the grid data to Excel: http://www.telerik.com/support/kb/aspnet-mvc/grid/export-to-excel.aspx

Related

Kendo UI DropDownListFor Set SelectedValue

I'm working with Kendo UI on an MVC application. We have a grid and when the user opens the row for editing we have a dropDownList that holds company names. I'm trying to get the DDL to default to the company name that's pertinent to the row.
Here's the column code:
columns.Bound(e => e.company_business_name).Width(220).Title("Company")
.EditorTemplateName("CompanyName");
and here's the editorTemplate code:
#model string
#(Html.Kendo().DropDownListFor(m => m)
.DataTextField("Text")
.DataValueField("Value")
.BindTo((System.Collections.IEnumerable)ViewData["Companies"])
)
and the method that fills the DDL:
private void PopulateCompanies()
{
var companyList = new List<SelectListItem>();
if (!string.IsNullOrEmpty(Session["Companies"] as string))
{
companyList = (List<SelectListItem>)Session["Companies"];
}
else
{
companyList = new DataAccess().GetCompanies(CurrentSettings.getUser().userId);
CacheCompanies(companyList);
}
ViewData["Companies"] = companyList;
}
EDIT:
Updated the code. The DDL still populates but I'm still not getting the selected value when I click "edit" on the grid row. Feel like I'm close here, help!
The problem is that your Editor Template's model is your entire model, not the company_business_name property (Very bad name for a property, by the way. You need to follow the standard naming conventions).
You don't even need to fill the drop down list.
Your Editor Template should be something like this:
#model string
#(Html.Kendo().DropDownListFor(m => m)
.DataTextField("Text")
.DataValueField("Value")
.DataSource(x =>
x.Read(read => read.Action("GetCompanies", "AddEntry"))
)
)

Kendo UI ASP.Net MVC ForeignKey column DataSource in InCell Edit mode

I have Kendo Grid and a ForeignKey column on a page. ForeignKey column is populated using ViewData as described below.
column.ForeignKey(x => x.ProductID, (List<Product>)ViewData["products"], "ID", "ProdName");
The Grid is editable in batch(InCell) mode as show below...
.Editable(editable => editable.Mode(GridEditMode.InCell)
I want to modify collection of ProductID column in the grid after page is loaded based on value selected on other drop-down defined outside of the Grid.
How can I achieve that? Can I do it using jQuery?
Similar example I found here...
http://www.telerik.com/community/forums/aspnet-mvc/grid/cascading-dropdowns-in-grid-edit---foreignkey-columns.aspx
Thanks.
I figured out how to filter the Product drop-down using an EditorTemplate for the foreign key column.
Here is my column definition for the Product.
c.ForeignKey(x => x.ProductID, (List<Product>)ViewData["products"], "ID", "ProdName").EditorTemplateName("ProductIDEditor");
Here is the editor template for Product, ProductIDEditor.cshtml
#using Kendo.Mvc.UI
#(Html.Kendo().DropDownListFor(m => m)
.AutoBind(false)
.OptionLabel("Select a value...")
.DataTextField("ProdName")
.DataValueField("ID")
.DataSource(dataSource =>
{
dataSource.Read(read => read.Action("FilterProducts", "Home").Data("filterProducts"))
.ServerFiltering(true);
})
)
#Html.ValidationMessageFor(m => m)
In my main VIEW Index.cshtml, I added filterProducts JavaScript handler, that passes JSON object for productID to controller.
function filterChargeTypes()
{
return {
productID: $("#ProductID").val()
};
}
Here is the controller that listens to filtering event...
public ActionResult FilterProducts(string productID)
{
// do your filtereing based on productID.
}
FilterProducts will be called every time when user hits the drop-down to get filtered value.
You don't need the Editor Template. It will bind to a dropdown without it. You can use this, like you had, just minus the template:
c.ForeignKey(x => x.ProductID, (List<Product>)ViewData["products"], "ID", "ProdName")
or
c.ForeignKey(x => x.ProductID, (System.Collections.IEnumerable)ViewData["products"], dataFieldValue: "ID", dataFieldText: "ProdName")
And for filtering, you can just invoke .Filterable() on the grid.

Loop through IEnumerable in #Html.DropDownListFor (MVC3)

I have a collection of models that I am passing to my view and I want to display each model.property in the dropdownlist. The problem is there is a bug in my code where it shows two duplicate items.
#model IEnumerable<UserManager.Models.vw_UserManager_Model>
#Html.Label("BRAD Module:")&nbsp
#Html.DropDownListFor(model => model.FirstOrDefault().module_name, Model.Select(x => new SelectListItem { Text = x.module_name, Value = x.module_name }), new { id = "ddlSelectedBrad", onchange = "chkSelection()" })
I am currently using FirstOrDefault() to access the module name for each model in my collection of models. But by doing this I have a duplicate value.
See screenshots below:
MARKET:LEISURE is showing twice
Intelligence is showing twice. If I change this dropdown value and return to this screen it will show two duplicate values.
Summary
Does anyone know a better way of writing the LINQ query?
Thanks.
Instead of
Model.Select(x => new SelectListItem { Text = x.module_name, Value = x.module_name })
Try
Model.GroupBy(x => x.module_name).Select(x => new SelectListItem { Text = x.First().module_name, Value = x.First().module_name })
This should filter the duplicate records.

Telerik MVC3 Razor Grid - Partial View returning from Controller

I have a view with several controls that are used for searching. When a user searches (Ajax.BeginForm) off of these I return the data into a PartialView (Telerik MVC3 Grid) that was generated dynamically.
This all works fine. In the grid are buttons for selecting a row. When I select a row, it posts to my controller, I do some "stuff" etc. When I try to get back to the view all I get is my grid data on a page by itself, it displays like a table with no borders, no other controls etc. My code is below.
My partial grid:
#model Highlander.Areas.Highlander.Models.ViewModels.DeliveriesGridViewModel
#using System.Data;
#(Html.Telerik().Grid<System.Data.DataRow>(Model.Data.Rows.Cast<System.Data.DataRow>())
.Name("Grid")
.DataKeys(dataKeys => dataKeys.Add("DeliveryID"))
.Columns(columns =>
{
columns.Command(commandbutton =>
{
commandbutton.Select().ButtonType(GridButtonType.ImageAndText);
}).Width(80).Title(ViewBag.Title);
columns.LoadSettings(Model.Columns as IEnumerable<GridColumnSettings>);
})
.DataBinding(dataBinding => dataBinding.Server().Select("_MarkSystem", "Deliveries"))
.EnableCustomBinding(true)
.Resizable(resize => resize.Columns(true))
)
My Controller:
[GridAction]
public ActionResult _MarkSystem(GridCommand command, int id)
{
string shipDeliver = DataCache.ShipDeliver;
DataTable fullTable = DataCache.FullTable;
// call to function to get the datatable data based on the id
rHelpers.GetDataTableRow(id, fullTable, shipDeliver);
// get the data for the grid into the model
fullTable = DataCache.FullTable;
model = new DeliveriesGridViewModel();
model.Data = fullTable;
model.Columns = rHelpers.NewColumns(DataCache.FullTable);
return PartialView("_DeliveryGrid", model);
//if (Request.IsAjaxRequest())
//{
// return PartialView("_DeliveryGrid", model);
//}
//return PartialView("_DeliveryGrid", model);
//return PartialView("DeliveryManager", model);
}
As you can see I have tried various things with no success.
Can anyone give me some direction on this.
Thanks for your time.
As far i understand you are using dataBinding.Server() that call a server side binding. Use .Editable(editing => editing.Mode(GridEditMode.InLine) it will work.
Both kind of bindings (Server and Ajax) needs a editing mode. Put an editing mode and try again.Kindly Response if it does not work for you. Here full code of data binding:
**.DataBinding(dataBinding => dataBinding.Ajax()
.Select("myAction", "myController")
.Update("myAction",myController")).
Editable(editing => editing.Mode(GridEditMode.InLine))**

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