Kendo Editor Templates (Grid) - kendo-ui

I'm trying to populate a dropdownlist for use in my Kendo Grid using Editor Templates.
My StatesEditor.cshtml contains:
#(Html.Kendo().DropDownList()
.Name("State")
.DataValueField("StateID")
.DataTextField("ShortName")
.BindTo((System.Collections.IEnumerable)ViewData["states"]))
In my Controller I have:
public ActionResult Index()
{
var db = new ACoreEntities();
db.Configuration.ProxyCreationEnabled = false;
var states = db.StateLookups;
var stateList = states.Select(state => state.ShortName);
ViewData["states"] = stateList;
return View("~/Views/System/PMarkup/Index.cshtml");
}
In my actual grid, when I click the 'Edit' button for the row I get a dropdownlist that contains 51 'undefined' entries.

I ended up creating a State model then in my ActionResult I changed my code to:
ViewData["states"] = new ACoreEntities()
.StateLookups
.Select(s => new State
{
Id = s.StateID,
ShortName = s.ShortName
})
.OrderBy(s => s.ShortName);

Related

Telerik MVC Panel Bar getting reloaded for each Panel Bar Item action

I am using Telerik MVC Panel Bar as a side menu bar for my application. I am referring this link Demo
I did bind(Local Data Binding) my Model to the Panel Bar, which is working fine. My question is How do I make the Panel Bar Item.Action("Action","Controller") to be an AJAX call. Because every time I click on a menu my Page gets reloaded.
I am unable to find any solution for this in Telerik MVC section.
Any Help would be appreciated.
you can define the URL for the data source.
This example comes from Telerik documentation.
View
#(Html.Kendo().PanelBar()
.Name("panelbar")
.DataTextField("Name")
.DataSource(dataSource => dataSource
.Read(read => read
.Action("GetEmployeesJson", "Controller")
)
)
)
Action in Controller
public JsonResult GetEmployeesJson(int? id)
{
var dataContext = new SampleEntities();
var employees = from e in dataContext.Employees
where (id.HasValue ? e.ReportsTo == id : e.ReportsTo == null)
select new
{
id = e.EmployeeID,
Name = e.FirstName + " " + e.LastName,
hasChildren = e.Employees1.Any()
};
return Json(employees, JsonRequestBehavior.AllowGet);
}

Kendo UI TreeView: Add only nodes not exisisting in the view

I have tree view on a page which gets data from a ComboBox and a multiselect. The ComboBox contains the name of each ingredient and the multiselect contains the possible amount types which are then used as names for all their child nodes.
The tree looks something like that:
Ingredient 1
100mg
200mg
Ingredient 2
50mg
100mg
Everything works fine except I can add the same value twice because I am not able to validate if a node already exists.
Here is the function I am using to add new elements:
var addElement = function () {
var treeview = $("#ingredientTree").data("kendoTreeView");
var multiselect = $("#ingredientAmount").data("kendoMultiSelect");
var ingredientToAdd= $("#ingredient").val();
// I allways get an empty array at this point.
var exinstingIngredient= treeview.findByText(ingredientToAdd);
var children = new Array();
var amount = multiselect.value();
for (var j = 0; j < amount.length; j++) {
children.push({ text: amount[j] });
}
// it allways adds the items because the length is allways 0
if (exinstingIngredient.length === 0) {
treeview.append({
text: ingredientToAdd,
items: children
});
}
}
I don't understand why it can't find the existing element even I set its name as text and search for this text.
edit:
Here we have the treeview:
#(Html.Kendo().TreeView().TemplateId("treeview-template").Name("ingredientTree"))
That is the source of the ingredients, it handles just plain strings:
#(Html.Kendo().ComboBox()
.Name("ingredient")
.DataSource(source => source.Read(r => r.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "InternationalIngredients" }))))
.Events(events => events.Change("onIngredientChanged"))
)
Following you find the source for amounts, which handles strings to:
#(Html.Kendo().MultiSelect()
.Name("ingredientAmount")
.DataSource(source => source.Read(read => read.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "InternationalIngredientAmount" })).Data("getIngredient")).ServerFiltering(true)))
This is a function to determine the selected ingredient for the service call:
function getIngredient() {
return { ingredient: $("#ingredient").val() }
}
I've found the reason for my problem now. findByText seems to check the Content of the nodes span with class "k-in". Unfortunatly, this Content is modified when you add a template as described here. So if you want to find an element with template, you should use findById or you define your template in a way you can use jQuery.

How to enable devexpress MVC upload control on client side

I have a problem when I try to enable MVC upload control. The upload control is initially disabled. I want the upload control to be enabled when the user select an option in CheckBoxList. UploadControl does not allow changing its enabled state on the client side but how to do that. Can you help me and give me some example how to do that with postback or otherwise.
Place UploadControl inside a CallbackPanel.
#Html.DevExpress().CallbackPanel(settings =>
{
settings.Name = "CallbackPanel";
settings.CallbackRouteValues = new { Controller = "Home", Action = "CallbackPanelPartial" };
// other settings
settings.SetContent(() =>
{
using (Html.BeginForm("UploadControlUpload", "Home", FormMethod.Post))
{
Html.DevExpress().UploadControl(s =>
{
s.Name = "UploadControl";
s.CallbackRouteValues = new { Controller = "Home", Action = "UploadControlUpload" };
// other settings
s.Enabled = (bool)ViewData["UPEnabled"];
}).Render();
}
});
}).GetHtml()
We will store a variable that will indicate if the UploadControl is enabled in ViewData. So, I get its value on the CallbackPanel partial view. On our view, we will render the CallbackPanel in the following way:
#Html.Action("CallbackPanelPartial", new { CPEnabled = false })
And our controller method to process callbacks to the CallbackPanel is:
public ActionResult CallbackPanelPartial(bool CPEnabled) {
ViewData["UPEnabled"] = CPEnabled;
return PartialView("_CallbackPanelPartial");
}
When you check a CheckBox, send a callback to the CallbackPanel to enable the UploadControl. For this, handle the CheckBox CheckedChanged client side event.
#Html.DevExpress().CheckBox(settings =>
{
// other settings
settings.Properties.ClientSideEvents.CheckedChanged = "function (s, e) { CallbackPanel.PerformCallback({CPEnabled: true}); }";
}).GetHtml()

Kendo UI Grid: Method "removeRow" deletes all events of the grid

I have a Kendo UI Grid and added mouse events to the grid by jQuery (e.g. click). This is working without any problem. But by deleting a row in the grid, all events of the grid are also deleted. What am I doing wrong?
This is my code to delete a row:
var rowToDelete = $(this).closest("tr");
var grid = $("#gridId").data("kendoGrid");
grid.removeRow(rowToDelete);
I added a button to each row of the grid, added a click event to these buttons which deletes the corresponding row. After the row is deleted, the click events of all other buttons are removed. The same with the mouse-over events of a grid column.
Thanks for your help!
Please try with the below code snippet.
VIEW
<script>
function gridDataBound(e) {
var grid = $("#Grid").data("kendoGrid");
grid.tbody.find(">tr").click(function () {
$("#divTest").html('Row Index Clicked :' + $(this).index());
});
}
function DeleteRow(obj) {
var rowToDelete = $(obj).parent().parent()
var grid = $("#Grid").data("kendoGrid");
grid.removeRow(rowToDelete);
}
</script>
#(Html.Kendo().Grid<MvcApplication1.Models.TestModels>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(p => p.ID);
columns.Bound(p => p.Name);
columns.Template(#<text></text>).ClientTemplate("<input type='button' class='k-button' value='Delete' onclick='DeleteRow(this);' />");
})
.Pageable()
.Sortable()
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Grid_Read", "Home"))
)
.Events(e => e.DataBound("gridDataBound"))
)
<div id="divTest"></div>
CONTROLLER
public ActionResult Grid_Read([DataSourceRequest] DataSourceRequest request)
{
List<TestModels> models = new List<TestModels>();
for (int i = 0; i < 5; i++)
{
TestModels t1 = new TestModels();
t1.ID = i;
t1.Name = "Name" + i;
models.Add(t1);
}
return Json(models.ToDataSourceResult(request));
}
MODEL
public class TestModels
{
[Display(Name = "ID")]
public int ID { get; set; }
[Display(Name = "Name")]
public string Name { get; set; }
}
Let me know if any concern.
You are not posting all the code so I have to guess...
What is happening is that you set an event handler associated to the elements just after the initialization and therefore for some particular HTML elements but there are circumstances under which Kendo UI grid gets regenerated (basically the system removes the table and generates a new one).
If you want to set an event handler not for the current table content but for any future one, you might use jQuery on event but using three arguments where the second is the selector (in previous version of jQuery this was achieved with live function but now is deprecated, so if your jQuery version supports it better use on).
What you have to do is:
$("#grid").on("click", ".my-selector", function(e) {
var rowToDelete = $(this).closest("tr");
var grid = $("#gridId").data("kendoGrid");
grid.removeRow(rowToDelete);
});
Where my-selector is a CSS class attribute that you probably already set for identifying the remove button.

how to load a partial view on button click in mvc3

I have a DDL, on its change I load a partial view _GetX. Right now I am using it like this
#Html.DropDownListFor(model => model.XId, Model.XList, "Select", new { GetUrl = Url.Action("GetX", "Route") })
I need to load this partial view on clicking a button. How do I do this?
Assuming your GetX controller action already returns the partial view:
$(function() {
$('#someButton').click(function() {
// get the DDL. It would be better to add an id to it
var ddl = $('#XId');
// get the url from the ddl
var url = ddl.attr('GetUrl');
// get the selected value of the ddl to send it to the action as well
var selectedValue = ddl.val();
// send an AJAX request to the controller action passing the currently
// selected value of the DDL and store the results into
// some content placeholder
$('#somePlaceholder').load(url, { value: selectedValue });
return false;
});
});

Resources