This is my telerik code where the column text should be if Column value IsApproveReject = 0 then it should be pending, if 1 then approved, if 2 then rejected text should be come.
How can i achieve this in linq syntax.
#(Html.Telerik().Grid(Model)
.Name("Grid")
.Columns(columns =>
{columns.Bound(typeof(int), "IsApproveReject").Title(#Html.R("Status"));
})
.ClientEvents(events => events.OnComplete("onComplete"))
Thanks in Advance
There are several ways to do it.
You can do it directly in the view, close to what you were thinking :
columns.Bound(model => model.IsApproveReject == 0 ? "Pending" : "Rejected").Title("Status")
Second way (which is cleaner) is to do it by creating a new property in your model (are you working with a view model by the way ? or directly with the model ?)
In the model :
public string Status
{
get
{
return IsApproveReject == 0 : "Pending" : "Rejected";
}
}
And in the view :
columns.Bound(model => model.Status)
Related
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.
I have this code
#Html.RadioButtonFor(model => model.LivStato, 1, Model.LivStato == 1)
#Html.RadioButtonFor(model => model.LivStato, -1, Convert.ToString(Model.LivStato) == string.Empty)
If Model.LivStato == 1 is true, the radio button is checked.
I don't understand why if Convert.ToString(Model.LivStato) == string.Empty is true, the radio button is not checked
I also try this
#Html.RadioButtonFor(model => model.LivStato, -1, !Model.LivStato.HasValue)
but don't work.
In the model:
public short? LivStato { get; set; }
Can anyone help me?
Updated answer
Oops, my original answer did not work if the null radio button was not first in the list. As noted by #sohtimsso1970, the radio button would have a checked attribute which would normally cause it to be selected even when the value is not null unless there was another checked radio button later down in the DOM, which of course there would be if the true/false-bound radio button came below null-bound one.
With this in mind, here's a better solution:
#{
var dict = new Dictionary<string, object>();
if (!Model.LivStato.HasValue) { dict.Add("checked", "checked"); }
}
<label>#Html.RadioButtonFor(model => model.LivStato, "", dict) Null</label>
<label>#Html.RadioButtonFor(model => model.LivStato, 1) +1</label>
<label>#Html.RadioButtonFor(model => model.LivStato, -1) -1</label>
This will work regardless of where the null-bound radio button is on the DOM and also renders the correct HTML.
Original answer:
Using the following radio button will bind to null:
<%: Html.RadioButtonFor(model => model.LivStato, "", new { #checked = !Model.LiveStato.HasValue }) %>
The checked attribute is required so the radio button is correctly checked when the ViewModel property is null.
Look at HtmlHelper.RadioButtonFor overloads : no one uses a boolean third parameter as "check button if value == something". Third parameter (when it exists) is just here for htmlAttributes.
http://msdn.microsoft.com/en-us/library/ee830415%28v=vs.108%29
If your firstLine works, it's just because you use 1 as second parameter (Model.LivStato == 1 doesn't do anything).
You may try (untested)
#Html.RadioButtonFor(model => model.LivStato, 1)
#Html.RadioButtonFor(model => model.LivStato, -1)
and change -1 to null in your controller.
My grid:
#( Html.Telerik().Grid<eGate.BackOffice.Core.Model.UI.EgateMenuRevisionViewData>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(c => c.ParentId)
.Aggregate(a => a.Count()).ClientGroupHeaderTemplate(Html.ActionLink("Create a Revision for This Menu", "Edit", "Thing", new { menuid = "<#= Key #>" }, null).ToString());
columns.Bound(c => c.ParentName);
columns.Bound(c => c.ThingName);
})
.Groupable(grouping => grouping.Groups(groups => {
groups.Add(c => c.EgateMenu.EgateMenuId);
}).Visible(false))
This works. But it gives me:
Create a revision for this menu
1 Parent 1 Thing 1.1
1 Parent 1 Thing 1.2
1 Parent 1 Thing 1.3
Create a revision for this menu
2 Parent 2 Thing 2.1
2 Parent 2 Thing 2.2
2 Parent 2 Thing 2.3
And while that works, I'd much rather something more intuitive like:
Create a thing for parent 1
Thing 1.1
Thing 1.2
Thing 1.3
Create a thing for parent 2
Thing 2.1
Thing 2.2
Thing 2.3
Problem 1:
Create a thing for... needs to pass the ParentId to the actionlink but it needs to display the ParentName for the client yet only one exists in the aggregate at a time.
Problem 2:
I want to group by the Id without displaying the Id column in the results. But setting the column to visible(false) supresses the clientgroupheadertemplate.
Adding Visible(false) to the column binding suppresses the whole column itself from even being rendered in the client html - hence the suppression of the ClientGroupHeaderTemplate.
I would either try adding ParentId as a data key - e.g.
.DataKeys(keys =>
{
keys.Add(k => k.ParentId);
}
I think this would only help if you were using the built in grid (AJAX or Server) DataBinding though (for Insert at least). With an ActionLink however... I don't have much experience with using mvc html helpers in client templates - but if you said the orignal example worked with it, shouldn't something like this work as well?
columns.Bound(c => c.ParentId).ClientTemplate("")
.Aggregate(a => a.Count()).ClientGroupHeaderTemplate(Html.ActionLink("Create a thing for \"<#= ParentName #>\"", "Edit", "Thing", new { menuid = "<#= Key #>" }, null).ToString());
I added a blank ClientTemplate, which I assume would work so that the ID is not displayed.
Have you tried hiding the unwanted columns?
#( Html.Telerik().Grid<eGate.BackOffice.Core.Model.UI.EgateMenuRevisionViewData>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(c => c.ParentId).Visible(false);
.Aggregate(a => a.Count()).ClientGroupHeaderTemplate(Html.ActionLink("Create a Revision for This Menu", "Edit", "Thing", new { menuid = "<#= Key #>" }, null).ToString());
columns.Bound(c => c.ParentName).Visible(false);
columns.Bound(c => c.ThingName);
})
According telerik :
You can specify now Aggregate property with following values: Sum, Min, Max, Last, First, Count, Avg & Custom for every GridBoundColumn and the grid will calculate these aggregates if ShowFooter is set to true. In case of Custom aggregate the grid will raise event OnCustomAggregate where you can set desired result using e.Result.
So try First, Last or Custom options for every GridBoundColumn and set ShowFooter property to false.
<telerik:GridBoundColumn Aggregate="First" DataField="CustomerID" DataType="System.String"
HeaderText="CustomerID" SortExpression="CustomerID" UniqueName="CustomerID">
</telerik:GridBoundColumn>
I think it must be answered already!
Something like :
#Html.EditorFor(model => model.UserDept)
Just the UserDept has few options, so I want to be get choices by users in radio or checkbox and this textbox can get the value, :)
It's usually done with dropdown list, because there is a helper for it.
First, you have to populate data for that select list in your controller, like this:
public ActionResult Edit(int id)
{
ViewBag.PossibleMembers = memberRepository.All;
return View(projectRepository.Find(id));
}
Then in your view, you can use:
#Html.DropDownListFor(model => model.MemberId, ((IEnumerable<RunDog2.Models.Member>)ViewBag.PossibleMembers).Select(option => new SelectListItem {
Text = (option == null ? "None" : option.Name),
Value = option.MemberId.ToString(),
Selected = (Model != null) && (option.MemberId == Model.MemberId)
}), "Choose...")
You can get this code generated with MvcScaffolding for example.
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())