I am developing a MVC with kendo UI grid. In which I have grid and one Button. Grid contains check-box. When We click on button check box value(true/false) and Record id should go to action result.
using (Html.BeginForm("Update", "Model"))
{
Html.Kendo().Grid(Model.Users)
.Name("grid")
.Columns(columns =>
{
columns.Bound(o => o.UserName).Width("300px");
columns.Bound(o => o.IsLicensed).Template(o =>
{%><%: Html.CheckBox("license",o.IsLicensed)%> <%: Html.Hidden("id", o.UserId) %><%}).Width("200px");
})
.Resizable(resize => resize.Columns(true))
.Sortable(sorting => sorting.Enabled(true))
.Filterable(f => f.Enabled(true))
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(new int[] {10, 20, 50, 100})
.ButtonCount(5))
.Render();
%>
<p>
<input class="k-primary k-button" type="submit" value="Save" name="selectedValues"/>
</p>
<%
Html.EndForm();
}
%>
</div>
<% });
And my actionresult looks as below
public ActionResult Update(string[] license, string[] id)
Now here I am using ajax binding and giving datasource. So I can't use Template. We need to use ClientTemplate. ClientTemplate code changes are shown as below.
.Columns(columns =>
{
columns.Bound(o => o.UserName).Width("300px");
columns.Bound(o => o.IsLicensed).Width("300px").ClientTemplate("<input type='checkbox' name='license' ${ IsLicensed == true ? checked='checked' : ''} enabled />" + "<input type='hidden' name='id' value='#= UserId#' />");
})
.DataSource(datasource => datasource.Ajax().Read(read => read.Action("Customers_Read", "UsersLicensing")).PageSize(10))
.Render();
In previous case when Update actionresult is called both parameter are array of 10 as pagesize is 10 and I can update database. But in this case(with ajax and clientTemplate) id parameter is coming as array of 10 items but license parameter depends on number of checkbox selected(if 3 checkbox is selected then license contains 3 element). So I can't make one to one mapping.
Can anybody help me with this or suggest any better idea?
Try this....Worked for me
columns.Template(#<text></text>).
ClientTemplate("<input type='checkbox' class='chkbx' onclick='chkRoleChkBox(this)'
value='#=RoleId#' # if (DefaultRoleflag == 'Y') { # disabled='disabled' # } #/>").Width(30);
You should be able to change your client template as such:
.ClientTemplate("<input type='checkbox' name='license' ${ IsLicensed == true ? checked='checked' : ''} enabled value='#= UserId#' />")
Put the UserId directly into the value of the checkbox. Then when you post, instead of getting an array of "true" you should get an array of the value (which is the UserId) for the checked items.
Update
If you want to be able to get both the checked and unchecked lists, then you can add the hidden field back to the ClientTemplate.
.ClientTemplate(
"<input type='checkbox' name='license' ${ IsLicensed == true ? checked='checked' : ''} enabled value='#= UserId#' />" +
"<input type='hidden' name='id' value='#= UserId#' />"
)
Then when you post you will have an array of all of the IDs in string[] id and an array of the checked IDs in string[] license. Then to get the unchecked, you can use use System.Linq namespace and use Enumerable.Except.
public ActionResult Update(string[] license, string[] id)
{
//....
var unchecked = id.Except(license).ToArray();
//...
}
I have a Kendo grid and a Save button on top of the page. When I click on “Add New Record” toolbar, a new row is added in the grid (client side). When I click on save button, I get the updated viewmodel in my controller’s action method which in turns add/update data in the database.
Now, I want to restrict adding a row in the grid if the grid has already 5 rows in it which means user will not be able to add a new row if the grid reaches its limit (which is 5 rows).
Can anyone of you please give me a sample client side script(jquery) that will restrict user to add new row in the grid?
Thank you very much!!!!!!!
Index.cshtml
#using (Html.BeginForm("Save", "UDF", FormMethod.Post))
{
<input class="button" type="submit" name="save" value="Save"/>
#(Html.Kendo().Grid(Model.List1)
.Name("List1")
.HtmlAttributes(new { style = "width:auto;height:100%" })
.ToolBar(toolbar => toolbar.Create().Text("Add New Record"))
.Editable(editable => editable.Mode(GridEditMode.InCell).CreateAt(GridInsertRowPosition.Top))
.Columns(columns =>
{
columns.Bound(p => p.Title)
.ClientTemplate("#= Title #" +
"<input type='hidden' name='DateFields[#= index(data)#].Title' value='#= Title #' />")
.Title("Title").HtmlAttributes(new { style = "width:30%" });
columns.Bound(p => p.MaxPrecision).Title("Decimal Places")
.ClientTemplate("#= MaxPrecision #" +
"<input type='hidden' name='DateFields[#= index(data)#].MaxPrecision' value='#= MaxPrecision #' />");
columns.Bound(p => p.IsObsolete).Title("Obsolete")
.ClientTemplate("#= IsObsolete #" +
"<input type='hidden' name='DateFields[#= index(data)#].IsObsolete' value='#= IsObsolete #' />");
})
.DataSource(datasource => datasource
.Ajax()
.Model(model =>
{
{
model.Id(p => p.Title);
model.Field(p => p.Title).Editable(true);
model.Field(p => p.MaxPrecision).Editable(true);
model.Field(p => p.IsObsolete).Editable(true);
}
}
)
)
)
}
You can use the toolbar template, like the one demonstrated here.
The template can look something like this:
<button class="k-button" id="myAdd">My Custom Add</button>
Once the Grid is initialized you can attach click handler which adds the new row based on your condition.
$('#myAdd).click(function(){
var gr = $('#gridName').data('kendoGrid');
if(gr.dataSource.data().length<5){
gr.addRow();
}
})
The methods used above are all covered in the documentaion.
I have page with DropDownList and Telerik's Kendo UI Grid Control. When first time page is opened DropDownList has no item selected in it. When user selects value in DropDownList only then Grid should make Ajax call to the server and load corresponding data.
My code works fine when user selects item in DropDownList, but the problem is that first time when page is opened I there is no value in DropDownList and Grid should not make a call to the server.
My question is how can I prevent grid not to make a call to the server if there is no item selected in DropDowList?
<div>
#Html.Kendo().DropDownList().Name("broker").DataTextField("GrandParentName").DataValueField("Id").BindTo(Model).SelectedIndex(#selectedIndex).Events(e => e.Change("brokerChanged"))
</div>
#(Html.Kendo().Grid<OrderViewModel>()
.Name("Orders")
.HtmlAttributes(new {style = "height: 500"})
.Columns(c =>
{
c.Bound(p => p.Id)
.Width(50)
.Title("")
.Sortable(false)
.IncludeInMenu(false)
.ClientTemplate((#Html.ActionLink("Edit", "Index", "Splits", new {Id = "OrderId"}, null).ToHtmlString().Replace("OrderId", "#=Id#")));
c.Bound(p => p.TradeDate)
.Title("Trd Dt")
.Format("{0:d}")
.Width(90)
.HtmlAttributes(new {style = "text-align: right"});
c.Bound(p => p.Price)
.Title("Price")
.Format("{0:n}")
.Width(100)
.HtmlAttributes(new {style = "text-align: right"});
c.Bound(p => p.Status)
.Title("Status");
c.Bound(p => p.Notional)
.Title("Notional")
.Format("{0:n}")
.HtmlAttributes(new {style = "text-align: right"});
})
.Sortable()
.Scrollable()
.ColumnMenu()
.Pageable(x =>
{
x.Enabled(true);
x.PreviousNext(false);
x.PageSizes(false);
x.Info(true);
x.Input(false);
x.Numeric(false);
x.Refresh(true);
x.Messages(y => y.Display("{2} Order(s)"));
})
.Resizable(resize => resize.Columns(true))
.Reorderable(reoder => reoder.Columns(true))
.DataSource(ds => ds.Ajax()
.ServerOperation(false)
.Read(read => read.Action("Action", "MyController").Data("selectedBrokerId")))
)
<script type="text/javascript">
function brokerChanged() {
var grid = $("#Orders").data("kendoGrid");
grid.dataSource.read();
}
function selectedBrokerId() {
var obj = { brokerId: $("#broker").data("kendoDropDownList").value() };
return obj;
}
</script>
Thanks a lot for your time and help.
There is an autobind function for the grid. You can use this to determine whether or not to read when the page first loads. This should work (assuming that selectedIndex determines if a dropdown value is selected):
#(Html.Kendo().Grid<OrderViewModel>()
.Name("Orders")
.HtmlAttributes(new {style = "height: 500"})
.AutoBind(selectedIndex > 0)
//rest of your grid declaration
I have a Telerik MVC Grid where I have a column as " select " , " edit" forwhich I have used Format Property to show Links to my ActionMethods . Now I want to show the selected Row text in Bold when someone clicks on " Select" / " Edit " link ?
How to achieve this using JQuery / Javascript ? Tried using RowAction but couldnt sort out this as I am using Format Property and Ajax.ActionLink for Select and Edit ActionLinks.
<% Html.Telerik().Grid(Model.GetLegends)
.Name("PaymentScheduleLegendGrid")
.ToolBar(toolBar => toolBar.Template(() =>
{
%>
<label style="height:10px; float:left;padding-right:230px;" >Legend</label>
<%= Ajax.ActionLink("Add", "AddLegend", "PaymentSchedule", new AjaxOptions { OnSuccess = "updateTarget", UpdateTargetId = "addlegend", HttpMethod = "Get" }, new { Style="text-decoration:underline;" })%>
<%
})).HtmlAttributes("style='background:none grey'")
.DataKeys(dataKeys => dataKeys.Add(m => m.LegendId))
.Columns(columns =>
{
// columns.Bound(m => m.Legend_color).ClientTemplate("<div><div style='float:right;text-align:left;width:80%'><#= legend_name #></div>" + "<div style='padding:3px;background-color:<#= legend_color #>;width:20px;height:15px'></div></div>").Title("Legend");
columns.Bound(m => m.LegendColor).Format(Html.ColorBlock("{0}").ToHtmlString()).Encoded(false).Title("");
columns.Bound(m => m.LegendId).Hidden(true).HeaderHtmlAttributes(new { #class = "newBack" }); ;
columns.Bound(m => m.LegendName).Title("");
columns.Bound(m => m.LegendId).Title("").Format(Ajax.ActionLink("Select", "Select", "PaymentSchedule", new { Id = "{0}" }, new AjaxOptions { OnSuccess = "updateTarget", UpdateTargetId = "AddPaymentSchedule", HttpMethod = "Get" }, new { Style = "text-decoration:underline;" }).ToHtmlString().Replace("{", "{{").Replace("}", "}}")).Encoded(false).Width(60);
columns.Bound(m => m.LegendId).Title("").Format(Ajax.ActionLink("Edit", "EditLegend", "PaymentSchedule", new { Id = "{0}" }, new AjaxOptions { OnSuccess = "updateTarget", UpdateTargetId = "addlegend", HttpMethod = "Get" }, new { Style = "text-decoration:underline;" }).ToHtmlString().Replace("{", "{{").Replace("}", "}}")).Encoded(false).Width(60);
})
// .RowAction(row => row.Selected = row.HtmlAttributes.Add("style", "background:#321211;"))
.Sortable()
.Selectable().HtmlAttributes("style=font:bold")
.DataBinding(databinding => databinding
.Ajax().Select("AjaxIndex", "Legend"))
.Pageable(pager => pager.PageSize(5))
.Render();
%>
This is my code and When user clicks on Select / Edit ActionLink ... Selected LegendName should be highlighted in bold . When I use Selectable property I am getting the selected row as highlighted ( new Background color for selected row which doesnt satisfy my requirement). Besides that I have one more requirement , I want to change the background color of my toolbar to GREY . Can you please help me
In order to apply certain style for certain table row you need to use CSS. For server side binding you can use the HtmlAttributes from RowAction. However I don't know (as you haven't described) how to determine if a row is selected inside the RowAction method. If you want a more concrete answer I suggest you attach a running project which shows the entire scenario in the forum thread which you opened in the Telerik forums.
If you want to do that client-side you can use jQuery:
<%: Html.Telerik().Grid().ClientEvents(e => e.OnLoad("onLoad")) %>
<script>
function onLoad() {
$(this).delegate("tr a", "click", function(e){
$(this).closest("tr").addClass("t-state-selected") // add the css class
.siblings()
.removeClass("t-state-selected") // remove css class from other rows
});
}
</script>
So far I have done this .
<style type="text/css">
#PaymentScheduleLegendGrid table thead
{
}
.newBack
{
background:none grey;
}
.newBoldtext
{
font-weight:bold;
color:red;
}
</style>
<script type="text/javascript">
function onLoad() {
$(this).delegate("tr a", "click", function (e) {
$(this).closest("tr").addClass("newBoldtext"); // or any other CSS class
});
}
</script>
<div>
<% Html.Telerik().Grid(Model.GetLegends)
.Name("PaymentScheduleLegendGrid")
.ToolBar(toolBar => toolBar.Template(() =>
{
%>
<label style="height:10px; float:left;padding-right:230px;" >Legend</label>
<%= Ajax.ActionLink("Add", "AddLegend", "PaymentSchedule", new AjaxOptions { OnSuccess = "updateTarget", UpdateTargetId = "addlegend", HttpMethod = "Get" }, new { Style="text-decoration:underline;" })%>
<%
})).HtmlAttributes("style='background:none grey'")
.DataKeys(dataKeys => dataKeys.Add(m => m.LegendId))
.ClientEvents(e => e.OnLoad("onLoad"))
.Columns(columns =>
{
columns.Bound(m => m.LegendColor).Format(Html.ColorBlock("{0}").ToHtmlString()).Encoded(false).Title("");
columns.Bound(m => m.LegendId).Hidden(true).HeaderHtmlAttributes(new { #class = "newBack" }); ;
columns.Bound(m => m.LegendName).Title("test");
columns.Bound(m => m.LegendId).Title("")
.Format(Ajax.ActionLink("Select", "Select", "PaymentSchedule",
new { Id = "{0}"}
, new AjaxOptions { OnSuccess = "updateTarget", UpdateTargetId = "AddPaymentSchedule", HttpMethod = "Get" }
, new { name = "SelectRow", Style = "text-decoration:underline;" }
).ToHtmlString().Replace("{", "{{").Replace("}", "}}")).Encoded(false).Width(60);
columns.Bound(m => m.LegendId).Title("").Format(Ajax.ActionLink("Edit", "EditLegend", "PaymentSchedule", new { Id = "{0}" }, new AjaxOptions { OnSuccess = "updateTarget", UpdateTargetId = "addlegend", HttpMethod = "Get" }, new { Style = "text-decoration:underline;" }).ToHtmlString().Replace("{", "{{").Replace("}", "}}")).Encoded(false).Width(60);
})
.Sortable()
.Selectable().HtmlAttributes("style=font:bold")
.DataBinding(databinding => databinding
.Ajax().Select("AjaxIndex", "Legend"))
.Pageable(pager => pager.PageSize(10))
.Render();
%>
I have a Telerik Grid in my View. I want to know if there is a way by which I can bind the Datakey of the selected row to the Model Property -
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site1.Master" Inherits="System.Web.Mvc.ViewPage<Mitek.MobileImagingTest3.Models.JobFileStatisticsModel>" %>
<% using (Html.BeginForm()) { %>
<div class="editor-label">
<br />
<label>Select Which Job:</label>
</div>
<div>
<%= Html.Telerik().Grid((IEnumerable<Mitek.MobileImagingTest3.Models.JobFileStatisticsModel>)ViewData["JobFilesDataList"])
.Name("JobFileGrid")
.EnableCustomBinding(true)
//.BindTo((IEnumerable<Mitek.MobileImagingTest3.Models.JobFileStatisticsModel>)ViewData["JobFilesDataList"])
.DataKeys(keys => keys.Add(o => o.JobFileId))
.Columns(columns =>
{
columns.Bound(o => o.JobFileId).Hidden(true);
columns.Bound(o => o.JobFileName).Title("Job File Name").Width(500);
columns.Bound(o => o.JobFileVersion).Title("Job File Version").Width(200);
columns.Bound(o => o.JobFileDateCreated).Title("Date Created").Format("{0:MM/dd/yyyy}").Width(300);
})
.HtmlAttributes(new { style = "width: 1000px; font-family:arial; font-size: .9em;" })
.ClientEvents(events => events.OnRowSelected("onRowSelected"))
.DataBinding(dataBinding => dataBinding.Ajax().Select("SelectJobFile", "Admin"))
.Pageable()
.Sortable()
.Selectable()
.RowAction(row =>
{
row.Selected = row.DataItem.JobFileId.Equals(ViewData["JobFileId"]);
//Model.JobFileId = ViewData["JobFileId"].ToString();
})
%>
</div>
<div>
</div>
<div>
<br />
<button type= "submit" name="button" class="t-button" >Run Report</button>
</div>
</div>
<% } %>
enter code here
<script type="text/javascript">
function onRowSelected(e) {
var id = e.row.cells[0].innerHTML;
alert(id);
}
</script>
My model is -
public class JobFileStatisticsModel
{
public string JobFileId { get; set; }
public string JobFileName { get; set; }
public string JobFileVersion { get; set; }
public string JobFileDateCreated { get; set; }
}
How do I bind the Datakey of the selected row in the Grid to the Model.JobFileId property?
Please help.
Thanks,
SDD
Change <Mitek.MobileImagingTest3.Models.JobFileStatisticsModel>
to <IEnumerable<Mitek.MobileImagingTest3.Models.JobFileStatisticsModel>>
Also replace
<%= Html.Telerik().Grid((IEnumerable<Mitek.MobileImagingTest3.Models.JobFileStatisticsModel>)ViewData["JobFilesDataList"])
with this line.
<%= Html.Telerik().Grid<Mitek.MobileImagingTest3.Models.JobFileStatisticsModel>(Model)
If you replace both of those it should fix your problem. This is how I am currently doing it so I think it will work. If it doesn't just leave me a message and I will see what else I can come up with.