fill kendo combo box parameter - asp.net-mvc-4

I have a kendo combobox Clients, and I fill his content with
.DataSource(
source =>
{
source.Read(read => { read.Action("GetAllClientsJSONCombo", "CrmCProfile"); });
})
Now, I have another kendo combobox ContactsClient, but I need pass the Id of the selected client in first combobox, like this:
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetAllContactsClientJSONCombo", "CrmCProfile", new object { Id_Cliente = (????????)});
})
.ServerFiltering(false);
})
Thanks.

It is fine if you dont write new object just specify the word new
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetAllContactsClientJSONCombo", "CrmCProfile", new { Id_Cliente = Model.Value});
})
.ServerFiltering(false);
})
OR
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetAllContactsClientJSONCombo", "CrmCProfile").Data("yourParameters");
})
.ServerFiltering(false);
})
<script>
function yourParameters(){
return {"Id_Cliente": yourParameterValue};
}
</script>
And make sure that on the server side, the name of the parameter (i.e, Id_Cliente) is same.
public JsonResult GetAllContactsClientJSONCombo(string Id_Cliente){
//your logic here
}

Related

Kendo MVC Group Paging

I have a kendo grid that shows around more than a million records and in its initial load, it takes more than a minute to display.
how can I use the kendo Grouppaging feature to minimize the load time so the page loads the group items on demand? Loading of the group items happens when a group is expanded. Any other options to speed up are also appreciated.
what it basically does is that based on the dropdown value it draws the kendo grid
<div>
#(Html.Kendo().DropDownList()
.Name("samplegrid")
.DataTextField("samplegrid")
.DataValueField("samplegrid")
.HtmlAttributes(new { style = "width:90%" })
.DataSource(source => source
.Custom()
.Transport(transport => transport
.Read(read =>
{
read.Action("infoDropdown_Read",
"sample").Type(HttpVerbs.Get);
})))
.Events(e =>
{
e.Select("onCheckSelectForDetail");
})
)
</div>
Here is the code for the Grid.
#(Html.Kendo().Grid<Portal.Data.Models.InfoModel>()
.Name("gridSummary")
.DataSource(dataSource => dataSource
.Ajax()
.Aggregates(aggregates =>
{
aggregates.Add(p => p.OutstandingCount).Sum();
})
.Group(groups =>
{
groups.Add(p => p.OfficeNumber);
})
.Batch(true)
.ServerOperation(false)
.Sort(sort => sort.Add(column => column.Date))
)
.Columns(columns =>
{
columns.Bound(c => c.OfficeState).Width(70)
.Title("xxxx");
columns.Bound(c => c.OfficeNumber).Width(70)
.Title("zzzz");
columns.Bound(c => c.OutstandingCount).Width(60)
.Title("yyyy");
})
)
and the controller looks like
public async Task<IActionResult> infoDropdown_Read(){
try{
var infoListSR = await _eService.GetInfoListAsync();
if (infoListSR.Failed){
Log.Error($"Unexpected error occured due to
{infoListSR.ErrorData.ApplicationErrorMessage}");
throw new DataException($"{infoListSR.ErrorData.ApplicationErrorMessage}");
}
return Json(infoListSR.ResultData, new JsonSerializerOptions() {
PropertyNameCaseInsensitive = false});
}
catch (Exception ex){
Log.Error($"Username: {User.Identity.Name} - Dropdown list Failed with
Exception: {ex}");
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
An option to boost the performance, you could use the server grouping along with virtualization:
Demo

CellTemplate and ContentTemplate not rendering properly in Devextreme ASP.NET Core

I have a datagrid, where for each item on the table I need to attach one or many documents. When you click the last column button, you should open a popup which then has the file uploader.
I'm trying to create the custom button in my Datagrid, which will open the custom popup that has the FileUploader widget, but the button is not rendering at all.
Instead of the button showing, this is the result.
\[%!function(){%\]\ [%DevExpress.aspnet.createComponent("dxButton",{"text":"Attach","onClick":function (e) { attachButtonClick(data) }},arguments\[0\])%\]\[%}("dx-" + new DevExpress.data.Guid())%\]
I'm imagining the same will happen even if the popup shows. Just this text which would seem to represent the file uploader.
This is my .chtml code for this part.
#(Html.DevExtreme().DataGrid<myModel>()
.ID("dataGrid")
.DataSource(ds => ds.Mvc().Controller("DataGridMaterials")
.LoadAction("Get")
.InsertAction("Insert")
.UpdateAction("Update")
.DeleteAction("Delete")
.Key("ID")
)
.Columns(columns => {
columns.AddFor(m => m.Equipment);
columns.AddFor(m => m.Client);
columns.AddFor(m => m.Number);
columns.AddFor(m => m.Address);
columns.AddFor(m => m.Phone);
columns.Add().Width(160).Alignment(HorizontalAlignment.Center).CellTemplate(#<text>
#Html.DevExtreme().Button().Text("Attach").OnClick("function (e) { attachButtonClick(data) }")
</text>);
})
.OnRowDblClick(#<text>
function MyHandler(selectedItem) {
var dataGrid = $("#dataGrid").dxDataGrid("instance");
var selectedRowsData = dataGrid.getSelectedRowsData();
var allData = selectedRowsData[0];
var id = allData.ID;
console.log(id);
$('#customPopup').dxPopup('instance').option('visible', true);
}
</text>)
.RowAlternationEnabled(true)
.Editing(editing => {
editing.Mode(GridEditMode.Row);
editing.AllowUpdating(true);
editing.AllowDeleting(true);
editing.AllowAdding(true);
})
.Selection(s => s.Mode(SelectionMode.Single))
.RemoteOperations(true)
)
#(Html.DevExtreme().Popup().ID("customPopup").Width(660).Height(540).Title("Attachments").Visible(false)
.ContentTemplate(#<text>
#(Html.DevExtreme().FileUploader()
.ID("file-uploader")
.Name("myFile")
.Multiple(true)
.Accept("*")
.UploadMode(FileUploadMode.UseButtons)
.UploadUrl(Url.Action("Upload", "FileUploader"))
.OnValueChanged("fileUploader_valueChanged")
)
</text>)
)
I based my solution on this sample app.
View
Custom popup
It's strange, I follow the sample codes you provide and it can work on my side. I am using Asp.net core 3.1 and Devextreme 20.1:
#model Order
#{
ViewBag.Title = "Index";
}
<h2>Home</h2>
#(Html.DevExtreme().DataGrid<Order>()
.ID("gridContainer")
.ShowBorders(true)
.DataSource(d => d.Mvc().Controller("Orders").LoadAction("Get").Key("OrderID").UpdateAction("Put"))
.Columns(columns => {
columns.AddFor(m => m.CustomerName);
columns.AddFor(m => m.OrderDate);
columns.AddFor(m => m.ShipCity);
columns.Add().Width(160).Alignment(HorizontalAlignment.Center).CellTemplate(#<text>
#Html.DevExtreme().Button().Text("Attach").OnClick("function (e) { attachButtonClick() }")
</text>);
})
.Selection(s => s.Mode(SelectionMode.Single))
.RemoteOperations(true)
)
#(Html.DevExtreme().Popup().ID("customPopup").Width(660).Height(540).Title("Attachments").Visible(false)
.ContentTemplate(#<text>
#(Html.DevExtreme().FileUploader()
.ID("file-uploader")
.Name("myFile")
.Multiple(true)
.Accept("*")
.UploadMode(FileUploadMode.UseButtons)
.UploadUrl(Url.Action("Upload", "FileUploader"))
)
</text>)
)
<script>
function attachButtonClick() {
$('#customPopup').dxPopup('instance').option('visible', true);
}
</script>

kendodropdownlist not binding value to model after post

I'm using kendo UI for my project. I have a kendo dropdownlist that I'm populating with json. I get the values in my dropdownlist but on post, the model doesn't get the selected value of the dropdownlist. I have been stuck on it for a day with no result. I'm not sure where I'm going. Please review the code
View:
#model IEnumerable<EntityFrameworkClasses.StaggingException>
#foreach (var item in Model)
{
#(Html.Kendo().DropDownListFor(modelItem => item.Level2)
.Name("Level2")
.HtmlAttributes(new { style = "width:10%" })
.OptionLabel("Select level 2...")
.DataTextField("Text")
.DataValueField("Value")
.BindTo((System.Collections.IEnumerable)ViewBag.Level2)
)
}
#(Html.Kendo().Grid(Model)
.Name("CashExceptionsGridTest")
.Columns(columns =>
{
columns.Bound(p => p.Category).Title("Category").Width(130);
columns.Bound(p => p.EnterText1).Title("Comments").Width(130);
columns.Bound(p => p.Dateoftransaction).Title("Date").Width(130);
columns.Bound(p => p.InternalLocalAmount).Title("InternalAmt").Width(130);
columns.Bound(p => p.ExternalLocalAmount).Title("ExternalAmt").Width(130);
})
.ToolBar(toolbar =>
{
//toolbar.Template("<a class='k-button k-button-icontext' onclick='customCommand()' href='#'></span>Cutom Command</a>");
toolbar.Create(); // The "create" command adds new data items.
toolbar.Save();// The "save" command saves the changed data items.
})
.Editable(editable => editable.Mode(GridEditMode.InCell)) // Use in-cell editing mode.
.HtmlAttributes(new { style = "height: 550px;" })
.HtmlAttributes(new { style = "height: 350px;" })
.Pageable(pageable => pageable
.Input(true)
.Numeric(false)
)
.Reorderable(r => r.Columns(true))
.Sortable()
.ColumnMenu()
.Scrollable(scr => scr.Height(430))
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.ServerOperation(false)
.Batch(true) // Enable batch updates.
.Model(model =>
{
model.Id(p => p.RowID); // Specify the property which is the unique identifier of the model.
model.Field(p => p.RowID).Editable(false); // Make the ProductID property not editable.
})
.Update("Editing_Update", "MultiTab")
.Create("Editing_Create", "MultiTab")
)
)
}
I have a kendo grid below which im not including for code brevity.
Controller:
public ActionResult GetLevel()
{
IEnumerable<SelectListItem> Level2 = db2.StaggingInternalCashExceptions.Where(x=>x.LoadID==loadid).Select(c => new SelectListItem
{
Value = c.Level2.ToString(),
Text = c.Level2
}).Distinct();
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Editing_Create([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<StaggingException> results)
if (results != null && ModelState.IsValid)
{
foreach (var result in results)
var entity = new StaggingException();
entity.RowID = result.RowID;
entity.Category = result.Category; //this is a textbox in the view for which i get the value
entity.Level1 = result.Level1; //gives null
//I'm adding those values to the db. Didn't include all that for the sake of keeping it short.
}
}
The grid has batch editing, once i hit on save changes, the grid's data is posted to the controller where i can see it in results. I cannot get the dropdown value though.
Any ideas or leads please.
Thank you.
Late to this post but I have had a similar issue, for those with the same problem of the value not being posted in the model, if your model value is a nullable int? (can't see from the above post...) then you need to configure the DropDownListFor as below to avoid the default value binding behavior to update the field with the selected item when the initial value is null. Hope this helps someone.
Html.Kendo().DropDownListFor(m => m)
.HtmlAttributes(new { data_value_primitive = "true" })

Updating Kendo grid row on column value change

I am working on an MVC .Net Framework v4.5 site using Kendo MVC controls. One of the pages uses a Kendo grid which is bound to the view model. When I edit a row, there is a field which uses a dropdownlist control, and when the selection is changed, the remaining fields in the row should be updated to reflect that newly selected item..I am doing this with a JSON call which then returns the new view model to use for that row. However, I cannot figure out how to tell the grid to use the data that was returned from that JSON call. Any ideas?
EDIT:
I have attached some code. The issue now is that I can get the grid's datasource to 'refresh', but in the UpdateGridSource jscript function, at the grid.dataSource.read() line, the grid is now out of edit mode, and if I go to edit the row, the data is reverted back to how it originally was
(VIEW)
#(Html.Kendo().Grid<RedFile.Models.QuickQuoteItemView>()
.Name("QuoteItems")
.Columns(c =>
{
c.Bound(p => p.Id).Hidden();
c.Bound(p => p.Description).EditorTemplateName("Combobox");
c.Bound(p => p.ItemQty);
c.Bound(p => p.ItemPrice).Format("{0:c}");
c.Bound(p => p.Total).ClientTemplate("#= kendo.format('{0:c}', Total) #").FooterHtmlAttributes(new { style = "text-align:right;" }).ClientFooterTemplate("#= kendo.format('{0:c}', sum)#").HtmlAttributes(new { style = "text-align:right;" }).Width(100);
c.Command(cmd => { cmd.Edit(); cmd.Destroy(); }).Title("Commands").Width(200);
})
.ToolBar(tb => tb.Create())
.ClientDetailTemplateId("subitems")
.Editable(eb => eb.Mode(GridEditMode.InLine).CreateAt(GridInsertRowPosition.Bottom))
.Events(e=>e.Edit("editGrid"))
.Scrollable()
.DataSource(ds => ds
.Ajax()
.ServerOperation(false)
.Aggregates(a =>
{
a.Add(p => p.LineTotal).Sum();
a.Add(p => p.Total).Sum();
})
.Model(model =>
{
model.Id(p => p.Id);
model.Field(p => p.LineTotal).Editable(false);
model.Field(p => p.ItemPrice).Editable(true);
})
.Read(read => read.Action("GridSelect", "QuickQuote", new { qqid = Model.Id })).ServerOperation(false)
.Create(create => create.Action("GridCreate", "QuickQuote", new { qqid = Model.Id }))
.Update(update => update.Action("GridUpdate", "QuickQuote"))
.Destroy(destroy => destroy.Action("GridDelete", "QuickQuote"))
)
)
<script type="text/javascript">
function dropDownSelectionChanged(e) {
var dataItem = this.dataItem(e.item.index());
UpdateGridSource(dataItem.Value);
}
function UpdateGridSource(DropDownValue) {
var grid = $("#theGrid").data("kendoGrid");
grid.dataSource.transport.options.read.url = '/Controller/refreshGridDataSource?selection=' + DropDownValue;
grid.dataSource.read();
}
</script>
(CONTROLLER)
public JsonResult refreshQuickQuoteTest2([DataSourceRequest] DataSourceRequest request, string selection)
{
QuickQuoteItem qqi = db.QuickQuoteItems.FirstOrDefault(p => p.ItemID == selection);
QuickQuote quickQuoteOriginal = qqi.QuickQuote;
QuickQuoteItemView qqiv = new QuickQuoteItemView();
IEnumerable<QuickQuoteItemView> return2;
qqiv.Id = qqi.Id;
qqiv.ItemID = qqi.ItemID;
qqiv.ItemPrice = qqi.ItemPrice;
if (Session["quickQuote"] != null)
{
QuickQuote qq = (QuickQuote)(Session["quickQuote"]);
if (Session["editingQuickQuoteId"] != null)
{
int row = Convert.ToInt32(Session["editingQuickQuoteId"]);
foreach (var item in qq.QuickQuoteItems)
{
if (item.Id == row)
{
QuickQuoteItem test = new QuickQuoteItem();
StandardItem stdItem = new StandardItem();
stdItem = db.StandardItems.Find(selection);
item.ItemPrice = stdItem.Price;
item.Description = stdItem.Description;
item.ItemID = stdItem.ItemId;
}
}
}
return2 = QuickQuoteItemViewItems(qq);
}
else
{
return2 = QuickQuoteItemViewItems(quickQuoteOriginal);
}
return Json(return2.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
You can use the grids Ajax binding to call your controller Update Action method
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(false)
.Model(model => model.Id(p => p.SampleId))
.Update(read => read.Action("SampleGrid_Update", "Controller")))
Then you need to decorate your methods datasource parameter with the DataSourceRequest attribute and return the ModelState as a DataSourceResult
[HttpPost]
public ActionResult SampleGrid_Update([DataSourceRequest] DataSourceRequest dsRequest, IEnumerable<SampleViewModel> viewModel)
{
if (viewModel != null && ModelState.IsValid)
{
// other code goes here...
}
return Json(ModelState.ToDataSourceResult());
}
You can view the samples and documentation on the Kendo website
Edit
You can bind your ajax call to the change event of your dropdownlist and when this returns you can refresh the grid data from the server using
$("#gridId").data("kendoGrid").dataSource.read();

How the pop up works in the KendoUI grid and how to bring the controls in the pop up in KendoUI ajax grid for MVC4

How the popup window works when the edit button is click and how to bring the three Combobox in the popup. I am really confused with the below code
Client side Code
//show server errors if any
function error_handler(e) {
if (e.errors) {
var message = "Errors:\n\n";
$.each(e.errors, function (key, value) {
if ('errors' in value) {
$.each(value.errors, function () {
message += this + "\n\n";
});
}
});
alert(message);
}
}
#(Html.Kendo().Grid(Model)
.Name("SchoolGrid")
.Columns(columns =>
{
columns.Bound(p => p.SchoolID).Width("80px");
columns.Bound(p => p.Name);
columns.Bound(p => p.Campus).Width("90px");
columns.Bound(p => p.StateCode).Width("90px");
columns.Bound(p => p.SectorCode).Width("95px");
columns.Bound(p => p.MDISurveyStartDate).ClientTemplate("#= (MDISurveyStartDate == null) ? 'Not Set' : kendo.toString(MDISurveyStartDate, 'dd/MM/yyyy') #").Width("90px");
columns.Bound(p => p.MDISurveyEndDate).ClientTemplate("#= (MDISurveyEndDate == null) ? 'Not Set' : kendo.toString(MDISurveyEndDate, 'dd/MM/yyyy') #").Width("90px");
columns.Command(command => { command.Edit(); command.Destroy(); }).Width("190px").HtmlAttributes(new { style = "text-align:center" });
})
.ToolBar(tb => tb.Create().Text("Add New School"))
.Editable(ed => ed.Mode(GridEditMode.PopUp).TemplateName("EditSchool").Window(w => w.Title("Add/Edit School Details").Name("editWindow").Width(600)))
.DataSource(dataSource => dataSource
.Ajax()
.Model(model => model.Id(p => p.ClientID))
.Events(e => e.Error("error_handler"))
.Read("Read_Schools", "School")
.Update("Update", "School")
.Create("Create", "School")
.Destroy("Destroy", "School")
)
)
Server Side Code:-
[HttpPost]
public ActionResult Update([DataSourceRequest] DataSourceRequest request, School school)
{
try
{
if (ModelState.IsValid)
{
string errMsg = "";
if (!_Service.UpdateSchool(school, out errMsg))
ModelState.AddModelError("UpdateSchool", errMsg);
}
}
catch (Exception ex)
{
ModelState.AddModelError("UpdateSchool", ex.Message);
}
return Json(ModelState.ToDataSourceResult());
}
There is code library which shows how to manipulate the content of the Window. Rest of the editing is possible through the edit event of the Grid (check documentation).