Telerik MVC3 Razor Grid - Partial View returning from Controller - asp.net-mvc-3

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))**

Related

Two Tabstrips with Two Kendo Grids

i want to load two kendogrid respective with two tabstrips. The requirement is when i click the tab then only grid should load. It should not load two grids when page loads
I accomplish that similar to what Supersnake describes by calling an Action on my Controller that returns a partial view:
#(Html.Kendo().TabStrip().Name("myTabStrip")
.Items(tabs =>
{
tabs.Add().Text("Tab1").LoadContentFrom("Tab1Load", "MyController", new { id = Model.ID }).Selected(true);
tabs.Add().Text("Tab2").LoadContentFrom("Tab2Load", "MyController", new { id = Model.ID });
})
.Events(e => e.Select("onTabSelect"))
)
My controller action:
[HttpGet]
public PartialViewResult Tab1Load(int id)
{
// load view model (vm) for partial
return PartialView("_Tab1Content", vm);
}
You could also just load the partial directly. Word of caution: when the tabs are loaded via AJAX it can affect jquery issues like validation. Grids should be fine though.

Paging is not working on GridMvc its Reloading the page

i have two method httpget as
public ActionResult MiReport()
{
return View();
}
and httppost as
public ActionResult GetReportView(string startdate,string enddate) {
ReportModel Obj = new ReportModel( startdate, enddate );
return PartialView("GetReportView",Obj );
}
I am binding grid as
#using GridMvc.Html
<div class="col-md-12">
<h4><strong>REPORT</strong></h4>
#Html.Grid(Model.lstReport).Columns(columns => {
columns.Add(c => c.rep).Titled("REP");
columns.Add(c => c.businessName).Titled("BUSINESS NAME");
columns.Add(c => c.contactNmae).Titled("CONTACT NAME");
}).WithPaging(10)
</div>
I am showing it on View its loading the first 10 row fine but when i am clicking on paging button its calling the Get method and page is getting reloded.
Please help me.
Thanks in Advance.
You need to have your grid be given a name like this (Index.cshtml):
.WithPaging(10, 10, "grid1")
Now in the Index method change it to :
public ActionResult Index(String grid1 = "")
Now when you click on the page, you will see page number in the url as grid1=3,this will be read into parameter grid1 of Index method.
Now in this method check:-
if (!String.IsNullOrEmpty(grid1))
{
//my grid was populated based on PersonnelId selected in some dropdown on the view.You can use the variable in which you stored your key.
id = TempData["TimeOffPersonnelID"].ToString();
}
Hope this helps!!

Kendo UI Grid: Configuration of the DataSource with Context Model

I am using ASP.Net Mvc 4 with Kendo UI grid.
I would like to perform more advanced features on the kendo UI grid (like exporting the sorted data from the grid to excel, adding filters, etc.). I need to configure the DataSource in my View and the "Read" method in the Controller. The grid is populated from a LINQ query and stored in the ViewBag.
Here is the razor code in my view Index.cshtml
#(Html.Kendo().Grid((IEnumerable<Reports.Models.Company>)ViewBag.ActComp)
.Name("grid")
.Columns(columns =>
{
columns.Bound(comp => comp.Name);
columns.Bound(comp => comp.DateCreated);
columns.Bound(comp => comp.Quarter).Sortable(false);
columns.Bound(comp => comp.Code);
columns.Bound(comp => comp.Enabled).Column.Title = "Active";
})
.Sortable()
.Groupable()
.Scrollable(src => src.Height(500))
)
Here is the Controller ActiveCompController.cs
namespace Reports.Controllers
{
public class ActiveCompController : Controller
{
private FSLContext fslData = new FSLContext();
public ActionResult Index()
{
ViewBag.ActComp = from b in fslData.Companies
where b.Enabled == true
orderby b.Name
select b;
return View();
}
I have seen a couple of different examples with .Ajax() like:
.DataSource(dataSource => dataSource // Configure the grid data source
.Ajax() // Specify that ajax binding is used
.Read(read => read.Action("Products_Read", "Home")) // Set the action method which will return the data in JSON format
However, it didn't work as my data is from a LINQ query not formatted in JSON. Also, I don't know what to write in the "Read" method.
Any thoughts on how to configure the Datasource and the controller with my configuration ?
It looks like your code is similar to the example for the Kendo Grid at
http://demos.kendoui.com/web/grid/index.html
I would start by setting up a ViewModel class for Company that would hold all of your columns for the grid similar to how they have a ProductViewModel in their example. For instance, you would have the following in your ViewModel:
Name, DateCreated, Quarter, Code, Enabled
If you navigate to ASP.NET MVC > IndexController.cs you'll see where they've defined their method:
public ActionResult Products_Read([DataSourceRequest] DataSourceRequest request)
From there you'll see that they wrapped their LINQ results into their ViewModels and returned them in JSON format. You're on the right track for setting up the DataSource for your grid. As far as the Controller goes, you would change
.Read(read => read.Action("Products_Read", "Home"))
to
.Read(read => read.Action("<YourMethodHere>", "Home"))
Which will allow you to modify the logic for the read. However, note the Read operation is simply used for populating the table, any other functionality (such as sorting) would be handled differently. For more information on sorting take a look here
http://demos.kendoui.com/web/grid/sorting.html

Telerik MVC specifying your own action router within a template column

I am using the latest version of Telerik MVC with ASP.NET MVC 3 and the Razor view engine.
I have the following column declaration:
column.Bound(x => x.Id)
.Template(x => Html.ActionLink("Edit", "Edit", new { id = x.Id }))
.Title("Action")
.Width(100);
I have created my own method that routes to this Edit action method which I would like to use but not sure how to?
public static object AdministrationCategoryEdit(this UrlHelper urlHelper, int categoryId)
{
Check.Argument.IsNotNull(urlHelper, "urlHelper");
return new { area = "Administration", controller = "Category", action = "Edit", id = categoryId };
}
How would I reference the above method in my column declaration and pass it through the category ID?
For example, if I want to use it with a button, then I would do something like:
$('#btnEdit').click(function () {
window.location = '#Url.RouteUrl(Url.AdministrationCategoryEdit(Model.Id))';
});
There is no perfect match for your requirement since all ActionLink methods have a separate parameter for the action. However, it should work with the following code even though the action is now specified twice.
column.Bound(x => x.Id)
.Template(x => Html.ActionLink("Edit", "Edit", Url.AdministrationCategoryEdit(x.Id)))
.Title("Action")
.Width(100);
An alternative would be to create an HTML helper similar to ActionLink that now only generates the route parameters but the complete code for a link.

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