Sending Additional Form Data in the Grid
Environment
Product | Telerik UI for ASP.NET Core Grid |
Progress Telerik UI for ASP.NET Core version | Created with the 2023.1.117 version |
Description
How can I pass a serialized form as an additional parameter to my controller when fetching data in the Telerik UI for ASP.NET Core Grid?
Solution
To achieve the desired results:
- Provide a function handler by using the
Data()
configuration option for theRead
method of the Grid. - To get the form field as key-value pairs, utilize the
serializeArray()
within the handler. - Traverse through each of the fields, and alter them into your required format, which will then be displayed as a JSON object.
- Map the external fields to the JSON object.
- Pass the JSON object in the return statement of the handler.
// Form
<form id="userForm">
<label for="FirstName">First name:</label>
<input type="text" id="FirstName" name="FirstName" value="John">
<label for="LastName">Last name:</label>
<input type="text" id="LastName" name="LastName" value="Doe">
</form>
// Grid
@(Html.Kendo().Grid<OrderViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.OrderID).Filterable(false);
columns.Bound(p => p.Freight);
columns.Bound(p => p.OrderDate).Format("{0:MM/dd/yyyy}");
columns.Bound(p => p.ShipName);
columns.Bound(p => p.ShipCity);
})
.Pageable()
.Filterable()
.HtmlAttributes(new { style = "height:550px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Read(read => read.Action("Orders_Read", "Grid").Data("dataHandler"))
)
)
<script>
function dataHandler(e){
var formArray = $("#userForm").serializeArray(); // Serialize the form data as an array.
var form = {};
for (var i = 0; i < formArray.length; i++) {
form[formArray[i]['name']] = formArray[i]['value']; // Map the current key-value pairs into the form variable object.
}
return {
model: form // Return the JSON object.
}
}
</script>
public class GridController : Controller
{
public ActionResult Orders_Read([DataSourceRequest] DataSourceRequest request, UserModel model)
{
// Custom read logic.
var result = GetData();
return Json(result.ToDataSourceResult(request));
}
}
public class UserModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
}