kendo multiselect for mvc clears the selected values on submit - kendo-ui

My kendo multiselect control as displays below clears the selected values on page submit. When i submit the page and it contains validations errors, the selected items in the multiselects get lost. Even though its gets fill in the HttpPost method of the controller. Please help me find a solution for this behaviour.
#(Html.Kendo().MultiSelectFor(m => m.GemeentesIds)
.HtmlAttributes(htmlAttrMultiselect)
.DataTextField("Name")
.DataValueField("Id")
.Placeholder(Model.Disabled ? "" : "Selecteer gemeentes indien van toepassing...")
.Value(Model.Gemeentes)
.AutoBind(false)
.DataSource(source => {
source.Read(read => {
read.Action("GetGemeentes", "General").Data("GemeenteFilter").Type(HttpVerbs.Post);
})
.ServerFiltering(false);
})
)
Controller:
if (model.GemeentesIds != null)
model.Gemeentes = _organisatorischeEenheidRepository.GetGemeentesByIds(model.GemeentesIds);

Try this and see if it helps. Also assign a Name attribute using Name() method. In your case, I think it should be Gemeentes.
So your multi-select code would look like:
#(Html.Kendo().MultiSelectFor(m => m.GemeentesIds)
**.Name("Gemeentes")**
.HtmlAttributes(htmlAttrMultiselect)
.DataTextField("Name")
.DataValueField("Id")
.Placeholder(Model.Disabled ? "" : "Selecteer gemeentes indien van toepassing...")
.Value(Model.Gemeentes)
.AutoBind(false)
.DataSource(source => {
source.Read(read => {
read.Action("GetGemeentes", "General").Data("GemeenteFilter").Type(HttpVerbs.Post);
})
.ServerFiltering(false);
})
)
Source link which helped me resolve a similar issue:
http://www.telerik.com/forums/multiselect-and-form-not-sending-values-back

Related

Kendo DataSource requestEnd event gets fired multiple times

I am using Telerik UI for ASP.NET MVC and i have grid defined as below
#(Html.Kendo().Grid<GridModel>()
.Name("grid")
.Columns(col =>
{
col.Bound(o => o.ID)
.ClientTemplate("<input class = 't-checkbox-selectrow' type='checkbox' value='#=ID#'/><label></label>")
.HeaderTemplate("<input class = 't-checkbox-selectallrows' type='checkbox' id='selectAll'/><label></label>")
.Sortable(false)
.Filterable(false)
.HtmlAttributes(new { #class = "t-gridcol-selectrow" })
.Width(40)
.Locked(true).Lockable(false);
col.Bound(o => o.StatusName).Width(150);
col.Bound(o => o.Deadline).Width(120);
col.Bound(o => o.Cost).Width(150);
})
.AutoBind(false)
.Pageable(x => x.PageSizes(UIConstants.PageSizes))
.Sortable(x => x.AllowUnsort(false))
.Resizable(resizing => resizing.Columns(true))
.Reorderable(reorder => reorder.Columns(true))
.Scrollable(s => s.Height("Auto"))
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(UIConstants.DefaultPageSizeMax)
.Read(read => read
.Action("GetData", "DataProvider"))
.ServerOperation(false))
)
Then in the JS file i am resetting the grid's page to 1 onRequestEnd, So user always goes back to first page whenever i fetch the data from remote service
$(function(){
var ds = $("#grid").data("kendoGrid").dataSource;
ds.bind("requestEnd", function (e){
e.sender.page(1);
})
})
As per the kendo's documentation
requestEnd
Fired when a remote service request is finished.
However the requestEnd event also gets fire on page change (and sorting). So when i change the page programmatic it fires the requestEnd event again and goes into loop. ( note requestEnd also gets fired when i change Page or Sort manually on UI)
Is this is by design or wrong documentation?
i did something like below. e.response will be only populated when requestEnds as part of response from server. In all other cases it will null.
dataSource.bind("requestEnd", function (e) {
if (e.status != "error" && e.response != null) {
// do soemething here
}
I would really like kendo team either fix the issue or create new event
This question was asked 3 years ago, but I am coming across it while looking up some other information. While I am here, I will answer it for others, as LP13 is likely not concerned about this anymore.
In the HTML Razer code, add the RequestEnd event to the DataSource. Here is an example:
#(Html.Kendo().Grid<GridModel>()
.Name("grid")
// (snip)
.DataSource(dataSource => dataSource
.Ajax()
.Events(o => o.DataBound("onDataBound"))
.PageSize(UIConstants.DefaultPageSizeMax)
.Read(read => read
.Action("GetData", "DataProvider"))
.ServerOperation(false))
)
Now in your jquery, you would write your event handler:
function onRequestEnd(e) {
console.log('onRequestEnd: e.response Object(The raw remote service response) = ', e.response);
console.log('onRequestEnd: e.sender kendo.data.DataSource(The data source instance which fired the event) = ', e.sender);
console.log('onRequestEnd: e.type String (The type of the request) = ', e.type);
}

Kendo Grid: Toolbar template issue

I have a grid that lists Road information and want a Toolbar Template that will allow me to filter the roads by choosing a Concession from a DropDownList. Something like this
My code:
CSHTML
<div id="datagrid">
#(Html.Kendo().Grid<SustIMS.Models.RoadModel>()
.Name("datagrid_Roads")
.Columns(columns =>
{
columns.Bound(r => r.RoadCode).Title(ViewBag.lblCode).Width(140);
columns.Bound(r => r.RoadType).Title(ViewBag.RoadType).Width(140);
columns.Bound(r => r.RoadMediumDescription).Title(ViewBag.lblDescription);
columns.Bound(r => r.ConcessionCode).Title("CCode").Hidden();
columns.Bound(r => r.ConcessionMediumDescription).Hidden().Title(ViewBag.Concession);
})
.ToolBar(toolbar =>
{
toolbar.Template(#<text>
<div class="toolbar">
<label class="category-label" for="category">Concessão:</label>
#(Html.Kendo().DropDownList()
.Name("concessions")
.OptionLabel("All")
.DataTextField("ConcessionMediumDescription")
.DataValueField("CCode")
.AutoBind(false)
.Events(e => e.Change("concessionChange"))
.DataSource(ds =>
{
ds.Read("ConcessionFiltering", "MasterData");
})
)
</div>
</text>);
})
.HtmlAttributes(new { style = "height: 534px;" })
...
)
)
</div>
<script type="text/javascript">
function concessionChange() {
var value = this.value(),
grid = $("#datagrid_Roads").data("kendoGrid");
if (value) {
grid.dataSource.filter({ field: "ConcessionMediumDescription", operator: "eq", value: value });
} else {
grid.dataSource.filter({});
}
}
Controller
public ActionResult ConcessionFiltering()
{
ConcessionModel cm = new ConcessionModel();
var aux = cm.getConcessions();
return Json(aux.concessions.Select(c => c.concession.mediumDescription).Distinct(), JsonRequestBehavior.AllowGet);
}
This is the current result:
The list is filled with the word "undefined" 16 times, which is the number of concessions I currently have. When I select one of the undefined options, it shows the actual name of the concession, refreshes the grid but doesn't filter it.
I want the list to show the concession names and to filter the grid by concession as I select one of them. What am I missing?
change this
return Json(aux.concessions.Select(c => c.concession.mediumDescription).Distinct(), hJsonRequestBehavior.AllowGet);
to
return Json(aux.concessions.Select(c => new ConcessionModel { Description = c.concession.mediumDescription }).Distinct(), JsonRequestBehavior.AllowGet);
First, double check what Json you are returning from the controller method. It looks like your ConcessionMediumDescriptions may have no data in them.
Second, it looks like, in your controller, that you are returning a list of "ConcessionMediumDescription" data objects.
I am guessing it looks like this...
{ConcessionMediumDescription: {
CCode: 'mycode',
...
}
}
You may consider returning a title field as a part of this Json and to use that for the text field of your dropdown. This is just me guessing from what you are returning in that controller.
Ideal Json would be somting like this...
[{
{{id: 'id1'},{text: 'text1'}},
{{id: 'id2'},{text: 'text2'}}
}]
And you defind your dropdown as such.
.DataTextField("text")
.DataValueField("id")
You have to do json return line like this.
return Json(aux.concessions.Select(c => new { Value = c.concession.DATAVALUE, Text = c.concession.DATATEXT }), JsonRequestBehavior.AllowGet);
Just change DATAVALUE and DATATEXT

Kendo UI Grid returns JSON to browser (using MVC)

I've recently purchased a Kendo subscription, I'm having trouble getting an AJAX bound grid to operate as expected, hoping someone here can help.
I have followed the Kendo docs tutorial # http://docs.kendoui.com/getting-started/using-kendo-with/aspnet-mvc/helpers/grid/ajax-binding
and could get the AJAX binding working nicely.
I've tried to now implement it into an existing MVC solution, and whenever I click the New or Edit command button, I get a string of JSON returned to the browser. Similiar to issue (JSON data to KENDO UI Grid ASP.NET MVC 4) But the answer in that problem didn't work for me.
Here is my Controller code...
public ActionResult Index()
{
// non-important code removed here //
var viewModel = newReferenceViewModel();
ViewBag.TradeReferences = TradeReferenceWorker.Get(applicationId);
return View(viewModel);
}
public ActionResult TradeReferences_Read([DataSourceRequest]DataSourceRequest request)
{
var applicationId = GetCurrentApplicationId();
DataSourceResult result = TradeReferenceWorker.Get(applicationId).ToDataSourceResult(request);
return Json(result, "text/x-json", JsonRequestBehavior.AllowGet);
}
And the View ....
#(Html.Kendo().Grid((IEnumerable<TradeReference>)ViewBag.TradeReferences)
.Name("gridTradeReference")
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
model.Id(tradeReference => tradeReference.TradeReferenceId);
model.Field(tradeReference => tradeReference.TradeReferenceId).Editable(false);
})
.Read(read => read.Action("TradeReferences_Read", "References"))
.Create(create => create.Action("TradeReference_Create", "References"))
.Update(update => update.Action("TradeReference_Update", "References"))
.Destroy(destroy => destroy.Action("TradeReference_Destroy", "References"))
)
.Columns(columns =>
{
columns.Bound(tref => tref.TradeReferenceId).Visible(false);
columns.Bound(tref => tref.Name);
columns.Bound(tref => tref.Phone);
columns.Command(commands =>
{
commands.Edit();
commands.Destroy();
}).Title("").Width(200);
})
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable.Mode(GridEditMode.InLine))
.Sortable()
)
So to sum up... the Grid will load perfectly the first time. I haven't wired up anything on the Edit / Delete actions, just trying to get Create operational. Clicking Add New, or even Edit for that matter will make the browser simply display Json to the screen.
It is hopefully something simple - thanks in advance
Solved it - the problem was the kendo js files were not being referenced correctly.
In my particular case, the bundling wasn't done 100% correctly so the Kendo javascript files were never getting included in the page.
They must also appear in a certain order, as described in the troubleshooting guide http://docs.kendoui.com/getting-started/using-kendo-with/aspnet-mvc/helpers/grid/troubleshooting

Kendo Grid EditorTemplateName DropDownList Id Not Posting

I have a simple kendo grid that I am trying to associate an editor template with. The foreign key is the only property that is sent down to the client so I can't give the editor template a model type of the foreign key property.
Configuration for Kendo Grid
protected override void Configure(GridBuilder<AreaModel> grid)
{
grid.Columns(c =>
{
c.Bound(a => a.Description);
c.Bound(p => p.CompanyId).ClientTemplate("#= CompanyDescription#").EditorTemplateName("DropDown/CompanyId").Width(160);
c.Command(command => command.Edit()).Width(200);
c.Command(command => command.Destroy()).Width(110);
});
grid.ToolBar(toolbar => toolbar.Create().Text("New Area"));
grid.Editable(edit => edit.Mode(GridEditMode.InLine));
grid.DataSource(d => d
.Ajax()
.Model(m => m.Id(p => p.Id))
.Create("GridInsert", "Area")
.Update("GridUpdate", "Area")
.Destroy("GridDelete", "Area"));
}
}
The editor template is straight forward as well. Everything works except that the value is not posted to the server.
#using Kendo.Mvc.UI
#(Html.Kendo().DropDownList()
.Name("CompanyId")
.DataValueField("Id")
.DataTextField("Name")
.DataSource(d => d.Read("CompaniesData", "Company")))
Can anybody help me out on this one?
modelview propoerty name which should maintain dropdownlist's selected value must be the Name of dropdownlist in editorTemplate and the type of datavaluefield and property should be same.

select Kendo ui grid row from controller

My first problem is : I use kendo grid with Single Select mode and I need when view loaded for the first time, the first row is selected, in other words, i want to select the first kendo grid row programatically.
moreover other problem is i insert radiobutton column in that grid , and i want synchronize
radiobutton select with row select , in other words, i want that when user select row,it causes it's radiobutton Selected
Please help me
tnx
this is the code:
#(Html.Kendo().Grid<CommonData.Domain.LegalEntityPhone>()
.Name("SMSGrid")
.HtmlAttributes(new { style = "width:800px;" })
.Selectable(selectable =>
selectable.Mode(GridSelectionMode.Single).Type(GridSelectionType.Row))
.Columns(columns =>
{
columns.Bound(c => c.Id)
.Title(" ")
.ClientTemplate(" <input type='radio' id='Approve' name='chkApprove' />");
columns.Bound(c => c.Number)
.Title("Destination")
.HeaderHtmlAttributes(new { style = "text-align: center;" })
.HtmlAttributes(new { style = "text-align: center; });
columns.Bound(c => c.CityCode)
.Title("City Code")
.Width(30)
.HeaderHtmlAttributes(new { style = "text-align: center" })
.HtmlAttributes(new { style = "text-align:center;width:30px" });
columns.Command(command => { command.Edit(); }).Width(150);
})
.Editable(editable => editable.Mode(GridEditMode.InLine))
.Events(events => events.Change("OnChange"))
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
model.Id(p => p.Id);
model.Field(p => p.Id).Editable(false);
})
.Read(read => read.Action("LegalEntityPhoneInfo_Read", "Message"))
.Update(update => update.Action("LegalEntityPhoneInfo_Update", "Message"))
)
)
There is no such thing as making the row selected in the controller because the Grid is all created on the client. You can use the dataBound event to make the first row selected.
e.g.
$(function(){
$('#GridName').data().kendoGrid.bind('dataBound',function(e){
this.select(this.tbody.find('>tr:first'));
})
})
Or use one instead of bind to make the row selected only when the page is loaded, not each time when the Grid is rebound - sort,filter, etc. Check documentation for more info.
If you are unfamiliar with jQuery, I highly recommend you take an online free tutorial from http://jqueryair.com/.
Assuming your project is referencing the jQuery script in your _Layout page, all you should have to do is add an Event handler for Databound to the grid:
.Events(events => events.DataBound("Grid_Databound"))
Then just paste this script onto the page:
<script>
function Grid_Databound() {
var grid = $("#MyGridName").data("kendoGrid");
row = grid.tbody.find(">tr:not(.k-grouping-row)").eq(0);
grid.select(row);
}
</script>
I'm sure the same script that zeinad added would work as well, always more than one way to skin a cat. As far as making the radio button show selected if the row is selected, I think if you watched the tutorial I mentioned, you should be able to figure it out. Post back if you need more help.

Resources