MVC | Kendo Grid | Pass the data from View to the controller - asp.net-mvc

I am using a kendoui Grid which is populated with some data. The grid has one Template column, of check-box and some other columns with Client Template that includes a Text-box in it.
I need to now pass the data of the rows, that are selected using a check-box, to the controller action.
The updated values in the text-box should be passed to the controller.
Let me know if anyone has the solution for the same.
This is the Grid
#(Html.Kendo().Grid<MMM.Lumos.Entities.CustomEntities.TestPlanTestPointMappingViewModel>()
.Name("ATPGrid")
.Columns(columns =>
{
columns.Bound(p => p.IsSelected).ClientTemplate("<input type='checkbox' value='#= IsSelected #' " + "# if (IsSelected) { #" + "checked='checked'" + "# } #" + "/>").Width(40);
columns.Bound(p => p.TestPointName).Filterable(false).Width(60);
columns.Bound(p => p.PassThreshold).ClientTemplate(Html.Kendo().IntegerTextBox().Name("mp_#=TestPointId#").Min(0).HtmlAttributes(new { value = "#=PassThreshold#", style = "width: 50px;" }).ToClientTemplate().ToHtmlString()).Width(60);
columns.Bound(p => p.FailThreshold).ClientTemplate(Html.Kendo().IntegerTextBox().Name("mp_#=TestPointId#").Min(0).HtmlAttributes(new { value = "#=FailThreshold#", style = "width: 50px;" }).ToClientTemplate().ToHtmlString()).Width(60);
})
.Scrollable()
//.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Read(read => read.Action("ATPGrid_Read", "TestPlan"))
)
)
I have a submit button
<input type="submit" name="Add" formmethod="post" onclick="PostData()" value="Add" />
Javascript function
<script>
function PostData() {
var griddata = $("#ATPGrid").data("kendoGrid");
alert(JSON.stringify({ griditems: griddata.dataSource.view() }));
//$.ajax(
// {
// type: 'POST',
// url: '/configuration/testplan/Add',
// dataType: 'json',
// contentType: "application/json; charset=utf-8",
// data: JSON.stringify({ griditems: griddata.dataSource.view() }),
// success: function (result) {
// alert('success');
// }
// });
}
</script>
I need to get the values of this grid on click of add button. As you can see i have a Client Template Columns, Check-box and Text-box in the grid.
I need to get the values from this text-box and pass it to the controller.
It would be great if only those which are selected using check-box should be passed to the controller.

I am not sure whether there is simple way of passing values from View to Controller in Kendo UI Grid. But i have followed the below way in third party MVC Grid to pass the checkbox values. You can bind this function to button click event. It could be too long for simple operation. May be it could be useful for you which you can optimize for your needs.
function PostData(sender, args) {
        var tempCheckedRecords = new Array();
        var gridobj = $find("Grid1"); // getting Grid object. Modify it for KendoUI grid.
        if (sender.checked == true) {
            ... //retrieve the records here
            tempCheckedRecords.push(records[0]); // pass the selected records in the array
        }
        var tempRecords = new Array();
        $.each(tempCheckedRecords, function (index, element) {
            var record = {};
            record["Column0"] = element.IsSelected; // column names in Grid
            record["Column1"] = element.TestPointName; // you can get the text box values in the element.
            record["Column2"] = element.PassThreshold;
            tempRecords.push(record);
        });
        var params = {};
        var visibleColumns = gridobj.get_VisibleColumnName();
        $.each(tempRecords, function (i, record) {
            $.each(visibleColumns, function (j, value) {
                params["Test[" + i + "]." + this] = record[value];
            });
        });
        $.ajax({
            type: 'post',
            url: "/configuration/testplan/Add",
            datatype: 'json',
            data: params,
            success: function (data) {
                return data;
            }
        });
    }

Explore adding an AJAX update call in your Kendo Grid:
.Datasource(datasource => datasource.Ajax
.Read(read => read.Action(...))
.Update(update => update.Update("UpdateAction", "Controller))
Then in your controller add an Action:
public ActionResult UpdateAction(IEnumerable<NewsModel> model)
{
//...do stuff
}

Related

How to add Checked Column in Kendo Grid

#model IEnumerable<Pardon.Models.ViewModel.StudendsShowCreatAddViewModel>
<h2>#ViewBag.Title</h2>
#(Html.Kendo().Grid(Model)
.Name("grid")
.Columns(columns =>
{
columns.Bound(model => model.ISSelected).Template(#<text></text>).ClientTemplate("<input type='checkbox' #= ISSelected ? checked='checked':'' # class='chkbx' />");
//columns.Bound(model => model.ISSelected)///Bound(model => model.ISSelected)
//.ClientTemplate("<input type='checkbox' #= ISSelected ? checked='checked' : '' # disabled='enabled' ></input>");
columns.Bound(model => model.CoursesSystem_ID).Visible (false);
columns.Bound(model => model.per_Name);
columns.Bound(model => model.per_Family);
columns.Bound(model => model.stu_ID).Visible (false);
})
.ToolBar(toolbar =>
{
toolbar.Custom().Action("CreateStudents", "CoursesSystem", new {_StudendsShowCreatAddViewModel = #Model }).Text("ثبت");
}
)
.Groupable()
.Pageable()
.Sortable()
.Scrollable()
.Filterable()
.DataSource(dataSource => dataSource
.Server()
)
)
<script>
$(function() {
$('#grid').on('click', '.chkbx', function() {
var checked = $(this).is(':checked');
var grid = $('#grid').data().kendoGrid;
var dataItem = grid.dataItem($(this).closest('tr'));
dataItem.set('ISSelected', checked);
});
});
</script>
I tried the above column properties Boolean ==>Isselected to checked Column and Editable and it didn't work.
For example, such as Photo
You're trying to add a client template showing a checkbox. I take a slightly different approach setting CSS classes so that when the row is not being edited I'll show a tick or cross depending upon the underlying value, then when the cell is clicked to start editing the checkbox is displayed. Optionally you can add additional CSS so the tick is coloured green and the cross red.
columns.Bound(a => a.ISSelected)
.ClientTemplate("<i class='fa fa-lg #: ISSelected ? 'fa-check' : 'fa-times' #'></i>")
.HtmlAttributes(new { #class = "text-center" })
.Title("Is Selected");
The above is using Font Awesome classes by the way.

Kendo Grid command.custom url

I am trying to get command.custom to work with a url. i have command.Custom("Tasks"); and it creates the button like it should. But i can't figure out how to get it to point to this url ../../OBClientSetupTasks/Index/#item.SetupID
I tried to make it do a .action and click through the controller and view but it returns a not supported exception
command.Custom("Tasks").Action("Index", "OBClientSetup");
I also can't seem to identify #item.SetupID . item is usually from a foreach, but in this case I don't see where a foreach would go.
EDIT:
Adding full grid
#(Html.Kendo().Grid<XXX_2_0_OBOE.OpenAccess.OBClientSetup>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(obcs => obcs.ProfileName);
columns.Bound(obcs => obcs.Default).ClientTemplate("#= Default ? 'Yes' : 'No' #");
columns.Bound(obcs => obcs.EEFinalize).ClientTemplate("#= EEFinalize ? 'Yes' : 'No' #");
columns.Bound(obcs => obcs.AllowOutsideCodes).ClientTemplate("#= EEFinalize ? 'Yes' : 'No' #");
columns.Bound(obcs => obcs.Completed).ClientTemplate("#= Completed ? 'Yes' : 'No' #");
columns.Command(command =>
{
command.Custom("Tasks").Action("Index", "OBClientSetup", new { SetupID = Model.SetupID });
command.Edit();
command.Destroy().HtmlAttributes(new { #class = "onboard-delete " });
});
})
.ToolBar(toolbar =>
{
toolbar.Template(#<text>
<div class="toolbar">
<div class="row">
<div class="col-md-3 pull-right">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></span>
<input type="text" class="form-control" id='FieldFilter' placeholder="Search Profile Name">
</div>
</div>
</div>
</div>
</text>);
})
.HtmlAttributes(new { #class = "table-responsive" })
.Groupable()
.Pageable()
.Sortable()
.Editable(editable => editable.Mode(GridEditMode.InLine))
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("OB2_ClientProfiles", "OB"))
.PageSize(5)
.Update(update => update.Action("EditingInline_Update", "OB"))
.Destroy(update => update.Action("EditingInline_Destroy", "OB"))
.Model(model => model.Id(obcs => obcs.SetupID))
)
)
The Model
public partial class OBClientSetup
{
private int _setupID;
public virtual int SetupID
{
get
{
return this._setupID;
}
set
{
this._setupID = value;
}
}
The idea is so they can click a button and be sent to OBClientSetupTasks/Index/1 or whatever their ID is
To use the Grid's model that way you'll probably need something like this:
Create a JavaScript function to handle the click event. Here you can grab the SetupID. I don't know what you're controller's action is going, but there are a few options.
If you want to change to the Index page, do something like this:
<script>
function SetupTasks(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
window.location.href = '#Url.Action("Index", "OBClientSetup")' + "/" + dataItem.SetupID;
}
</script>
Or, execute some ajax request like this:
<script>
function SetupTasks(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
windows.location.href = '#Url.Action("Index", "OBClientSetup")',
type: "POST",
dataType: "json",
data: { SetupID: dataItem.SetupID },
success: function (data) {
// Handle return value
}
});
}
</script>
In your grid specify your command button like this:
command.Custom("Tasks").Click("SetupTasks");

Kendo Window - LoadDataFrom finds argument value inline?

I have a kendo window which I want to populate depending on a selection made in a dropdown. I've tried refreshing the window upon open, but I can't figure out how to make that work. Changing gears, I'm wondering if I can instead send a variable parameter to the controller within window declaration itself, and then do a simple window.refresh (instead of coding the refresh to hit a specific controller, which isn't working).
I mean something like this:
#(Html.Kendo().Window()
.Name("EditWindow")
.Title("Edit Contact")
.LoadContentFrom("_ContactEdit", "Contacts", new { selectedContact = $("#ContactId").data("kendoComboBox").value() })
.Content("Loading...")
.Visible(false)
.Draggable()
.Resizable()
.Width(400)
.Modal(true)
.Actions(actions => actions.Pin().Minimize().Maximize().Close())
)
Or this:
#(Html.Kendo().Window()
.Name("EditWindow")
.Title("Edit Contact")
.LoadContentFrom("_ContactEdit", "Contacts", new { selectedContact = getContact() })
.Content("Loading...")
.Visible(false)
.Draggable()
.Resizable()
.Width(400)
.Modal(true)
.Actions(actions => actions.Pin().Minimize().Maximize().Close())
)
Obviously neither of these work, but I'm wondering if there's another way to fill in this field?
Thank you!
edit: Adding relevant code from controller and window/partial view. My controller is now being hit, but my window is not pulling the correct data. Any ideas?
Window:
#model [taking out company info].Contact
#using Kendo.Mvc.Extensions
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset id="infoForm">Hello, world.
#Html.HiddenFor(model => model.ContactId, new { id = "EditWindowId" })
<br />
<label id ="ContactNameID" style="width: 130px;">Contact Name</label>
<span>
#Html.TextBoxFor(model => model.FullName, new { type = "text", id = "EditWindowName", #class = "k-textbox form-control", style = "width: 200px; cursor:default" })
</span><br />
</fieldset>
}
Controller:
[HttpGet]
public ActionResult _ContactEdit(int selectedContact)
{
var entities = from r in dbContext.Contacts
where r.ContactId == selectedContact
select r;
if (entities.Any())
{ return PartialView(entities.First()); }
else
{ return HttpNotFound("Contact does not exist."); }
}
You can leverage the change event of your dropdown list to grab the selected value. Once you have the selected value you can programmatically refresh the window with the appropriate action on your controller. For example, the code below defines a Kendo DropDownList with a subscription to the change event. In the change, the value is used to build a dynamic url, and the kendo window is refreshed with that url:
<%= Html.Kendo().DropDownList()
.Name("dropdownlist")
...
.Events(e =>
{
e.Change("onChange")
})
%>
<script type='text/javascript'>
function onChange(){
var value = this.value(),
window = $("#EditWindow").data("kendoWindow");
window.refresh({
url: "/Contact/_ContactEdit?selectedContact=" + value
});
}
</script>

Submitting jquery dialog box using ajax call

I'm attempting to do a search using a jquery ui dialog box, and have the results also appear in a dialog box without any redirection on the actual page. I'm thinking an easy way of doing this is just to create my ui and have a < div id > surrounding the content, then replace the div with a view using an ajax call.
I've gotten the basics of this working, but... I have no clue how to pass the input field parameters to the incoming view/controller! It's currently not using submit() in any shape or form as this causes an unavoidable page redirect afaik.
My dialog contains standard text fields such as:
#Html.HiddenFor(model => model.Id)
<label>Customer Name</label>
#Html.TextBoxFor(m => m.Name, new { #class = "text ui-widget-content ui-corner-all" })
<label>EIN</label>
#Html.TextBoxFor(m => m.Ein, new { #class = "text ui-widget-content ui-corner-all" })
<label>State Tax ID Number</label>
#Html.TextBoxFor(m => m.StateTaxId, new { #class = "text ui-widget-content ui-corner-all" })
I have a placeholder for the dialog div
<div id="dialog-searchResults" title="Search Results" class="hide">
#using (Html.BeginForm("searchResults", "Customers", FormMethod.Post, new { #id = "searchResultForm" }))
{
<div id="SearchContents">a</div>
}
</div>
The ajax call
function InsertDialogDiv(ajaxUrl, divTable) {
var jsonData = {
"id": 0
};
$.ajax({
type: 'POST',
url: BASE_URL + ajaxUrl,
data: JSON.stringify(jsonData),
success: function (data) {
$(divTable).replaceWith(data);
},
error: function (xhr, ajaxOptions, thrownError) {
$(divTable).replaceWith(xhr.responseText);
}
});
}
Where ajaxUrl='Customer/SearchResults' as the path of the view.
Replacing the div in this way does trigger the Customer's controller to hit the SearchResults function, but as I'm not submitting, the model has all null values. How do I get my precious nuggets of information?
TY & Rat's off to ya!
PS: ASP.NET C# MVC4 Razor

How does the Kendo UI cascading DropdownList works?

Can Anyone explain to me the structures of this codes?
For an instance .Name("products") is the DropDownList name, I would like to know for what are those (what do you call this (Name, OptionLabel, etc.)) because it really confuse me. I'm stuck in creating a cascading DropDownList.
#(Html.Kendo().DropDownList()
.Name("products")
.OptionLabel("Select product...")
.DataTextField("ProductName")
.DataValueField("ProductID")
.DataSource(source => {
source.Read(read =>
{
read.Action("Type", "ComboBox")
.Data("filterProducts");
})
.ServerFiltering(true);
})
.Enable(false)
.AutoBind(false)
.CascadeFrom("categories")
)
<script>
function filterProducts() {
return {
categories: $("#categories").val()
};
}
</script>
<p>
<label for="orders">Orders:</label>
#(Html.Kendo().DropDownList()
.Name("orders")
.OptionLabel("Select order...")
.DataTextField("ShipCity")
.DataValueField("OrderID")
.DataSource(source => {
source.Read(read =>
{
read.Action("SubType", "ComboBox")
.Data("filterOrders");
})
.ServerFiltering(true);
})
.Enable(false)
.AutoBind(false)
.CascadeFrom("products")
)
<script>
function filterOrders() {
return {
products: $("#filterOrders").val()
};
}
</script>
.Name("orders"): This is the unique name to assign to the dropdown html element.
.OptionLabel("Select order..."): This is what the dropdown should display when no option is selected.
.DataTextField("ShipCity"): This is the property of the datasource that populates the dropdown options that should be displayed in the dropdown.
.DataValueField("OrderID"): This is the property of the bound datasource that populates the dropdown options that should be used as the value to bind to the underlying model of the view.
read.Action("SubType", "ComboBox"): This defines the Action and Controller that should be called to retrieve the collection that will populate the dropdown options
.Data("filterOrders"): this is used to assign parameters to the above read.Action method
.ServerFiltering(true):
.Enable(false): Whether or not the dropdown is enabled.
.AutoBind(false): Whether or not the dropdown should immediately bind to its dropdown datasource (or wait for the cascade from dropdown to be assigned a value)
.CascadeFrom("products"): The other DropDownList to cascade from. If AutoBind is false, then this dropdown will only bind to its options datasource once the other dropdown has been assigned a value by the user.

Resources