Adding a Common Function Delegate Handler on Events
Environment
Product | Telerik UI for ASP.NET MVC |
Description
How can I create common function handler that can be reused in different modules. But with supplemented parameters of different kind based on custom logic? For example, in the Telerik UI for ASP.NET MVC Grid columns.
Solution
In the context of Telerik UI for ASP.NET MVC Helpers, adding a function with additional parameters requires a given event to expose a delegate overload.
Most of the Telerik UI for ASP.NET MVC Components event handlers provide this overload. This allows you to subscribe to events by a Func
The following example demonstrates how to achieve the desired outcome:
- Utilize the .Click() configuration method in order to employ a delegate.
- Within the delegate, pass an anonymous function.
- Inside the anonymous function, call a common function handler with additionally passed arguments.
@(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.EmployeeViewModel>()
.Name("Grid")
.Columns(columns => {
columns.Bound(e => e.FirstName);
columns.Bound(e => e.LastName);
columns.Bound(e => e.Title);
columns.Command(command =>
{
command.Custom("ViewEnvelope")
.Click(@<text>
function(){
envelopeAction(event, "View")
}
</text>)
.Text("View")
.IconClass("k-icon k-i-envelop")
.HtmlAttributes(new { title = "View Envelope" });
command.Custom("ApproveEnvelope")
.Click(@<text>
function(){
envelopeAction(event, "Approve")
}
</text>)
.Text("Approve")
.IconClass("k-icon k-i-check-circle")
.HtmlAttributes(new { title = "Approve Envelope" });
command.Custom("RejectEnvelope")
.Click(@<text>
function(){
envelopeAction(event, "Reject")
}
</text>)
.Text("Reject")
.IconClass("k-icon k-i-cancel")
.HtmlAttributes(new { title = "Reject Envelope" });
}).Width(350);
})
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("CustomCommand_Read", "Grid"))
)
)
<script>
function envelopeAction(e, action){
switch(action){
case "View":
alert("View Action Clicked")
break;
case "Approve":
alert("Approve Action Clicked")
break;
case "Reject":
alert("Reject Action Clicked")
break;
}
}
</script>
For a runnable example based on the code above, refer to the REPL example on adding a common function delegate handler with additional parameters on events.