MVC Kendo grid pass dropdownlist value to update method - c#

I have a Kendo grid:
#(Html.Kendo().Grid<Grid>().Name("Grid")
.DataSource(ds => ds
.Ajax()
.Model(model => model.Id(m => m.ID))
.Read(read => read.Action("Grid_Read", "Sessions", new {sessionId = ViewBag.SessionID}))
.Update(update =>
update.Action("Grid_Update", "Sessions", new {
sessionId = ViewBag.SessionID, qcStateId = '????'}))
.PageSize(10)
.Batch(true)
)
.ToolBar(toolbar =>
{
toolbar.Template(
"| Set selected to: " + #Html.Partial("EditorTemplates/QCStatusHeader"));
}
)
QCStatusHeader:
#(Html.Kendo().DropDownList()
.Name("QCStatusHeader")
.DataValueField("Id")
.DataTextField("Name")
.BindTo((List<NomadBase.Web.ViewModels.Shared.QCStateViewModel>)ViewBag.PossibleQCStatesHeader)
)
How do I get the selected value from the QCStatusHeader dropdownlist into my update call to the controller?

Pretty simple solution, add the .Data option with a javascript method to return the currently selected value of the ddl.
.Update(update => update.Action("Grid_Update", "Sessions", new {sessionId = ViewBag.SessionID})
.Data("QCStatusHeaderValue"))
function QCStatusHeaderValue() {
var value = $('#QCStatusHeader').data("kendoDropDownList").value();
return { qcStateId: value };
}

Related

In Kendo MVC Grid, how can I use local values for grid initialisation then later use the read operation?

I have the initial values for the grid in my ViewModel. But if the user wants to update values, I want to update my database, then send back the updated values for the grid from the backend. The problem is that the Ajax Read is always called. But it shouldn't because the (initial) values are there in the ViewModel and bound to Grid.
I tried setting the AutoBind to false, but it does not work, I get an error. (Cannot set AutoBind if widget is populated during initialization)
#(Html.Kendo().Grid<MyClass>()
.Name("MyClassGrid")
.BindTo(Model.MyClassList)
.Columns(column =>
{
column.Bound(c => c.SomeProp).Title("Some Property");
})
.Scrollable()
.DataSource(ds => ds
.Ajax()
.Read(read => read.Action("GetMyData", "CheckBar", new { param1 = Model.ParamFirst}))))
I want to display the already stored values for my grid, and only use the read operation if I want to update the values in my database too.
#(Html.Kendo().Grid<SQDCDashboard.Core.ViewModels.SafetyIncidentViewModel>()
.Name("safetyincident-grid")
.Columns(columns =>
{
columns.Bound(c => c.CreatedAt).HtmlAttributes(new { style = "width: 22%" }).Format("{0:MM/dd/yyyy}");
columns.Bound(c => c.Type).HtmlAttributes(new { style = "width: 22%" });
columns.Bound(c => c.Description).HtmlAttributes(new { style = "width: 22%" });
columns.ForeignKey(c => c.ProductionLineId, (System.Collections.IEnumerable)ViewData["ProductionLines"], "Id", "Name").HtmlAttributes(new { style = "width: 22%" });
columns.Command(command => { command.Edit(); }).HtmlAttributes(new { style = "width: 12%" });
})
.ToolBar(toolbar => toolbar.Create().Text("New Safety Incident"))
.Editable(editable => editable.Mode(GridEditMode.InLine))
.DataSource(ds =>
ds.Ajax()
.ServerOperation(false)
.Model(model =>
{
model.Id(p => p.Id);
model.Field(p => p.ProductionLineId).DefaultValue(Model.DefaultProdLine);
})
.Read(read => read.Action("GetSafetyIncidentList", "Safety"))
.Update(update => update.Action("EditSafetyIncidentInLine", "Safety"))
.Create(create => create.Action("CreateNewSafetyIncident", "Safety"))
)
.HtmlAttributes(new { style = "height: 100%" })
.Sortable()
.Filterable()
.Pageable()
.Mobile()
)
Here is an example of my grid. The Update(update => update.Action("Action" , "Controller"))
is the method you are wondering about. For my code I did not have to pass a parameter in with my read, and I do not need to pass one in with my Update.
[HttpPost]
public ActionResult EditSafetyIncidentInLine([DataSourceRequest] DataSourceRequest request, SafetyIncidentViewModel sivm)
{
if (sivm != null && ModelState.IsValid)
{
SafetyIncident si = _safetyIncidentService.Find(sivm.Id);
si.Description = sivm.Description;
si.ProductionLineId = sivm.ProductionLineId;
si.ProdLine = _productionLineService.Find(sivm.ProductionLineId);
si.Type = sivm.Type;
_safetyIncidentService.Update(si);
sivm.Id = si.Id;
sivm.CreatedAt = si.CreatedAt;
}
return this.Json(new[] { sivm }.ToDataSourceResult(request, ModelState));
}
This method is the one that is called when the Update button is pressed. The update button is created with the columns.Command(command => { command.Edit(); }; and the Editable(editable => editable.Mode(GridEditMode.InLine)). If you want more clarification or if your question is different let me know. I never got an error with having my grid already initialized when I was updating values.

Using a tabstrip with datasource

I am pulling in a tabstrip to show details within a template on the kendo grid. I do my initial pull for the grid, but would like to use a separate datasource for the tabstrip. I only have one tab that holds all these detail. Is there a better way of achieving this? I do want to show everything in the table like the HTML shows, but want to pull it from its own datasource when the detail table is displayed.
I do it elsewhere successfully but that's with using a grid within the template.
Below is the grid code and the template code :
#(Html.Kendo().Grid<InvoiceVM>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(i => i.DarwinInvoiceNumber).Title("Invoice").ClientTemplate("<a href='" + Url.Action("Current", "PayrollInvoices", new { i = "#: InvoiceNumber#" }) + "' >#: DarwinInvoiceNumber#</a>").Width(100);
columns.Bound(i => i.DivisionID);
//columns.Bound(i => i.Date).Format("{0:MM/dd/yyyy}");
//columns.Bound(i => i.CheckDate).Format("{0:MM/dd/yyyy}");
columns.Bound(i => i.DateDisplay).Title("Date"); //09/26/2017 DS TFS # 2798
columns.Bound(i => i.CheckDateDisplay).Title("Check Date"); //09/26/2017 DS TFS # 2798
columns.Bound(i => i.Total).Format("{0:C}");
columns.Bound(i => i.Employees);
columns.Bound(i => i.Employees).Title("Checks").Width(100);
columns.Bound(i => i.TotalGross).Title("Gross Wages").Format("{0:C}");
})
.Sortable()
//.Selectable()
.Scrollable()
.ToolBar(tools => tools.Excel())
.Excel(excel => excel
.FileName("PayInvoices.xlsx")
.Filterable(true)
)
.Groupable()
.ColumnMenu()
.Pageable()
.Filterable()
.ClientDetailTemplateId("template")
.HtmlAttributes(new { style = "height:600px;" })
.Reorderable(reorder => reorder.Columns(true))
.Resizable(resize => resize.Columns(true))
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(15)
.Read(read => read.Action("Get_InvoicesRead", "PayrollInvoices"))
)
.Excel(excel => excel
.FileName("InvoiceList.xlsx")
.Filterable(true)
.AllPages(true)
//.ProxyURL(Url.Action("Excel_Export_Summaries_Save", "Reports"))
)
.Events(events => events.DataBound("dataBound"))
)
<script id="template" type="text/kendo-tmpl">
#(Html.Kendo().TabStrip()
.Name("tabStrip_#=DarwinInvoiceNumber#")
.SelectedIndex(0)
.Animation(animation => animation.Open(open => open.Fade(FadeDirection.In)))
.Items(items =>
{
items.Add().Text("Details").Content(
"<div class='invoice_details sub-table-background'>" +
"<table class='table table-bordered'><tr><td><label>Pay Period Begin:</label></td><td>#=kendo.toString(StartDate,'MM/dd/yyyy')#</td><td><label>FICA Med</label></td><td>#= kendo.toString(TotalFicaM,'c') #</td><td><label>Total Benefits</label></td><td>#= kendo.toString(TotalBenefits,'c') #</td></tr>" +
"<tr><td><label>Pay Period End:</label></td><td>#= kendo.toString(EndDate,'MM/dd/yyyy') #</td><td><label>FICA SS</label></td><td>#= kendo.toString(TotalFicaSS,'c') #</td><td><label>Credits</label></td><td>#= kendo.toString(TotalCredits,'c') #</td></tr>" +
"<tr><td><label>Net Wages:</label></td><td>#= kendo.toString(NetWagesPayRun,'c')#</td><td><label>FUTA</label></td><td>#= kendo.toString(TotalFUTA,'c') #</td><td><label>Fees </label></td><td>#= kendo.toString(TotalFees,'c') #</td></tr>" +
"<tr><td><label>Sales Tax:</label></td><td>#= kendo.toString(Tax,'c')#</td><td><label>SUTA</label></td><td>#= kendo.toString(TotalSUTA,'c') #</td><td><label>Amount Due</label></td><td>#= kendo.toString(AmountRemaining,'c') #</td></tr>" +
"<tr><td><label>Non Gross:</label></td><td>#= kendo.toString(TotalNonGross,'c') #</td><td><label>Worker's Comp</label></td><td>#= kendo.toString(TotalWC,'c') #</td><td></td><td></td></tr>" +
"</table></div>"
);
})
.ToClientTemplate()
)
</script>
Regarding the progress indicator, we use the Kendo Progress Indicator which we start on the select event and stop on the load event:
#(Html.Kendo().TabStrip().Name("myTabStrip")
.Items(tabs =>
{
tabs.Add().Text("T1").LoadContentFrom("Tab1", "Controller", new { Id = Model.Id });
tabs.Add().Text("T2").LoadContentFrom("Tab2", "Controller", new { Id = Model.Id });
tabs.Add().Text("T3").LoadContentFrom("Tab3", "Controller", new { Id = Model.Id });
})
.Events(e => e
.ContentLoad("onContentLoad")
.Select("onTabSelect")
)
)
Then this script:
<script type="text/javascript">
function onTabSelect() {
window.setTimeout(function() {
// Find the tabstrip and attach a progressbar
kendo.ui.progress($('div.k-tabstrip-wrapper'), true);
});
}
function onContentLoad() {
// Hide progress bar
window.setTimeout(function() {
kendo.ui.progress($('div.k-tabstrip-wrapper'), false);
});
}
</script>
You could probably roll your own indicator with same concept.

Kendo UI MVC grid popup mode insert mode model.set not working for DropDownList

I have a sample like this popup editing mode
I want to store my model while first inserting, and set default values.
#(Html.Kendo().Grid<License>()
.Name("popupGrid")
.Columns(columns =>
{
columns.Bound(p => p.LicenseId).Width(20).Hidden().HeaderHtmlAttributes(new { #title = "License" });
columns.ForeignKey(p => p.CustomerId, (System.Collections.IEnumerable)ViewData["customers"], "CustomerID", "CustomerName")
.Title("Customer").Width(200);
columns.Bound(p => p.VendorId).Width(20).HeaderHtmlAttributes(new { #title = "Vendor" });
columns.Bound(p => p.ProductId).Width(20).HeaderHtmlAttributes(new { #title = "Product" });
columns.Command(p => p.Edit().Text("Edit").HtmlAttributes(new { #title = "Edit" })).Width(80);
})
.ToolBar(toolbar => toolbar.Create().HtmlAttributes(new {#id ="MyAddButton" ,#title = "Add" }))
.Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("PopupEditView"))
.Events(e => e.Edit("onGridEdit").Save("onGridSave"))
.DataSource(dataSource => dataSource
.Ajax()
.Model(model => model.Id(p => p.LicenseId))
.Create(create => create.Action("Create", "Home").Type(HttpVerbs.Post))
.Read(read => read.Action("Read", "Home").Type(HttpVerbs.Post))
.Update(update => update.Action("Update", "Home").Type(HttpVerbs.Post))
)
)
<script>
var myModel;
function onGridSave(e) {
if (e.model.isNew()) {
myModel = e.model;
}
}
function onGridEdit(e) {
if (e.model.isNew()&&myModel!=null) {
e.model.set("CustomerId", myModel.CustomerId);
e.model.set("VendorId", myModel.VendorId);
e.model.set("ProductId", myModel.ProductId);
}
}
</script>
But it's not working.
following code is not working too :
$(e.container).find('input[name="CustomerId"]').data("kendoDropDownList").value(myModel.CustomerId);//it's not giving error. but CustomerId is null in model of create method
Actually I want to this. But I don't know how to update datasource while prevent closing window.
You might try configuring your dropdownlist with valuePrimitive: true
http://docs.telerik.com/kendo-ui/api/javascript/ui/dropdownlist#configuration-valuePrimitive

How to set column width to autofit in Kendo Grid MVC

I use to my page of Kendo grid that have multi columns.
I want set a column width to autofit and change width automatically.
Plz help me , thanks
#(Html.Kendo().Grid<GardeshKar.Models.v_marhaleh_marahel>()
.Name("grdMarahel_Gardeshkar")
.ToolBar(toolbar => toolbar.Custom().Name("btnAddMarhaleh").Text("اضافه").HtmlAttributes(new { id = "btnAddMarhaleh", href = "#" }))
.Columns(columns =>
{
columns.Bound(c => c.Code).Width(50).Title("کد");
columns.Bound(c => c.Desc).Width(150).Title("شرح");//Autofit
columns.Command(c => c.Destroy().Text("حذف")).Width(70).Title("عملیات");
})
.HtmlAttributes(new { style = "height: 380px;" })
.Scrollable()
.Sortable()
.Resizable(rl => rl.Columns(true))
.Selectable(sl => sl.Mode(GridSelectionMode.Single).Type(GridSelectionType.Row))
.DataSource(dataSource => dataSource
.Ajax()
.Model(m => m.Id(p => p.id))
.Read(read => read.Action("Get_DS_Marahel_Gardeshkar", "Home",
new { intGardesh = ViewBag.CodeGardeshKar }))
.Destroy(del => del.Action("Del_Marhaleh_GardeshKar", "Home")))
)
that column specific with autofit must column width change to autofit
One way is to remove the "Scrollable" property or you can use this function in dataBound event.
function Autocolumnwidth(e) {
var grid = e.sender;
for (var i = 0; i < grid.columns.length; i++) {
grid.autoFitColumn(i);
}
}

dropdownlist in kendo grid not working

Im trying to use incell editing and use of the http://demos.telerik.com/aspnet-mvc/grid/editing-custom but is can't find my partial view that the dropdownlist should be rendered from.
Partial view (Testview.cshtml)
#using Kendo.Mvc.UI
#(Html.Kendo().DropDownList()
.Name("ResourceType") // Name of the widget should be the same as the name of the property
.DataValueField("Id") // The value of the dropdown is taken from the EmployeeID property
.DataTextField("Name") // The text of the items is taken from the EmployeeName property
.BindTo((System.Collections.IEnumerable)ViewData["defaultResourceType"]) // A list of all employees which is populated in the controller
)
This is my grid:
#(Html.Kendo().Grid<RMS.Admin.ViewModel>()
.Name("ResourceGrid")
.Columns(columns =>
{
columns.Bound(c => c.ResourceId).Hidden();
columns.Bound(c => c.ResourceName);
columns.Bound(c => c.Descritption);
columns.Bound(c => c.ResourceType.Name).ClientTemplate("#=ResourceType.Name#");
columns.Bound(c => c.Approved);
columns.Bound(c => c.IsEnabled);
columns.Command(command =>
{
command.Edit();
command.Destroy();
}).Width(172).Title("Edit/Delete");
})
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Scrollable()
.Sortable()
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5))
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
model.Id(s => s.ResourceId);
model.Field(s => s.ResourceType).DefaultValue(ViewData["defaultResourceType"] as RMS.Admin.ViewModel.ResourceTypeId);
})
.Create(update => update.Action("CreateResource", "Home"))
.Read(read => read.Action("ReadResource", "Home"))
.Update(update => update.Action("SaveSystem", "Home"))
.Destroy(destroy => destroy.Action("RemoveSystem", "Home"))
)
)
Here is a part of my model:
public string ResourceUserId { get; set; }
[UIHint("Testview")]
public ResourceTypeId ResourceType { get; set; }
This is in my controller where i bind the data:
private void GetResourceTypeId()
{
//string [] list = new string[]{"Image", "Document", "Other"};
IList<ViewModel.ResourceTypeId> list = new List<ViewModel.ResourceTypeId>();
var a = new ViewModel.ResourceTypeId
{
Name = "Image",
Id = 1
};
var b = new ViewModel.ResourceTypeId
{
Name = "Document",
Id = 2
};
var c = new ViewModel.ResourceTypeId
{
Name = "Other",
Id = 3
};
list.Add(a);
list.Add(b);
list.Add(c);
ViewData["defaultResourceType"] = list.First();
}
I get this error when trying to render the grid:
The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
What am i missing?
First off your trying to bind just to one item with ViewData["defaultResourceType"] = list.First();. Instead you should bind to your whole list and then set the default option with .Value("1") so that it has "Images" by default.
#(Html.Kendo().DropDownList()
.Name("ResourceType")
.DataValueField("Id")
.DataTextField("Name")
.BindTo((System.Collections.IEnumerable)ViewData["ResourceTypeList"])
.Value(ViewData["DefaultResourceType"])
);
Also for a template for a column in MVC you may just want to set it with EditorTemplateName
columns.Bound(e => e.myColumn).EditorTemplateName("dropdownTemplate")
And then define the template that you want to use somewhere else on the page.
<script id="dropdownTemplate" type="text/x-kendo-template">
#(Html.Kendo().DropDownList()
.Name("myDropDown")
.....
.ToClientTemplate()
)
</script>
If you would like you can also declare it as a stand alone template in your /Views/Shared/ folder. You would not have to add the .ToClientTemplate() or the script tags. You would reference it by the file name. You could then use the template on multiple pages in the project.

Categories

Resources