Telerik Forums
UI for ASP.NET MVC Forum
1 answer
129 views
I am trying to put an AutoComplete field into a GridEdit Pop-up dialog.   I am using a custom template to format the listbox.  The problem is that the listbox shows everything as 'undefined'.  If I then click on a listbox item, the correct underlying value is selected and displayed properly.

If I copy the code, take it out of the PopUp editor, and paste it directly into the parent View, then it works perfectly.

Something else I tried...
If I remove the Template altogether than the listbox displays the correct value.  I just lose my custom formatting.

I've narrowed the problem down to being the Template.  I'm certain that there is something special you have to do with your Template if you are in a Pop-up dialog.  The data is not being binded correctly.

What should I do to make the Template work right?
@(Html.Kendo().AutoComplete()
    .Name("DiaryCodeAutoComplete")
    .Filter("startswith")
    .Placeholder("Select diary code...")
    .DataTextField("Code")
    .DataSource(source =>
    {
        source.Read(read =>
        {
            read.Action("GetSelectList", "DiaryCode");
        });
    })
    .Template("<span style='font-weight: bold;'>${data.Code}</span> <span style='float:right'>${data.Name}</span>")
)


Daniel
Telerik team
 answered on 21 Oct 2013
6 answers
637 views
Hello, fellow developers.

I'm new to Kendo UI and I am trying to create a grid in which each row actually consists of two lines: one long description above and the detail columns below. The only way I found to achieve this was with a ClientRowTemplate. My problem is that I am unable to add Kendo's widgets when using this template. Even more: I wasn't able to even find the controls inside the template with my jQuery selectors. Here's some sample code:

@(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.ProductViewModel>()
    .Name("grid")
    .HtmlAttributes(new { style = "width: 1100px;height:500px" })
    .Columns(columns =>
    {
        columns.Template(e => { }).Width(25);
        //columns.Bound(e => e.ProductName);
        columns.Bound(e => e.ProductFamily).Width(150);
        columns.Bound(e => e.ProductCode).Width(200);
        columns.Bound(e => e.Dimensions).Width(100);
        columns.Bound(e => e.Date.EditorTemplateName("DatePicker");
        columns.Bound(e => e.Unit).Width(80);
        columns.Bound(e => e.Quantity).Width(80);
        columns.Template(e => { }).Width(30);
    })
    .ClientRowTemplate(@"
    <tr class='line1'>
        <td style='font-size:larger'><div class='favorite'>*</div></td>
        <td colspan=13>#: ProductName #</td>
    </tr>
    <tr class='line2'>
        <td />
        <td class='details'>
            <span class='description'>#: ProductFamily #</span>
        </td>
        <td class='details'>
            <span>#: ProductCode #</span>
        </td>
        <td class='details'>
            <span>#: Dimensions #</span>
        </td>
        <td class='details'>
            <div class='dateControl'></div>
            <input type='text' class='datepicker' />
        </td>
        <td class='details'>
            <select>
                <option label='Mts' value='1' />
                <option label='Kgs' value='2' />
                <option label='Lts' value='3' />
            </select>
        </td>
        <td class='details'>
            <input type='text' size='1'/>
        </td>
        <td class='details'>
            <a href='javascript:void();' style='text-decoration:none'>
                <div>+</div>
            </a>
        </td>
   </tr>"
   )
    .DataSource(dataSource => dataSource
        .Ajax()
        .Read(read => read.Action("RowTemplate_Read", "Grid"))
        .Update(update => update.Action("RowTemplate_Update", "Grid"))
    )       
    .Scrollable()
)
 
@section HeadContent {
      <style>          
        .title {
            display: block;
            font-size: 1.6em;
        }
        .description {
            display: block;
            padding-top: 1.6em;
        }
        .line1 {
            border-top:thick !important;
            border-top-style:solid !important;
            border-top-color:red !important;
            border-bottom:none !important;
            margin-top:10px !important;
            background: linear-gradient(to bottom, rgba(0,0,0,0.05), rgba(0,0,0,0.10));
        }
        .line2 {
            grid-row:start !important;
            border-top:none !important;
            border-bottom:thick !important;
            margin-bottom:10px !important;
            background: linear-gradient(to bottom, rgba(0,0,0,0.10), rgba(0,0,0,0.15) 99% , rgba(0,0,0,0.8) 100%);
        }
    </style>
}
 
    <script id="dateTemplate" type="text/x-kendo-template">
        @(Html.Kendo().DatePicker().Name("dpDate").ToClientTemplate())
    </script>
    <script>
        $(function () {
            $(".datepicker").datepicker();
        });
 
        $(document).ready(function () {
            var tpl = kendo.template($("#dateTemplate").html());
            $(".dateControl").html(tpl({}));
        });
    </script>
A few comments about the code, what I need and what I tried:

  • The first line of the row has the product name and the second line its details. I had to remove the "product name" column from the Columns method in order to obtain my desired layout. It would be great if there is a way of including that column in the header, but this would mean there should be two column lines there, and I don't know if that's possible. This is a quick mockup I made with Excel so you get the picture. <datePicker> is of course where I want the widget to be.
  • I tried using an EditorTemplate in "e.Date.EditorTemplateName("DatePicker")" without luck either. Does this work if I use the ClientRowTemplate? Even if I remove the template call, this editor doesn't work. Just in case, this is the code I have in DatePicker.cshtml:
@model  Kendo.Mvc.Examples.Models.ProductViewModel
 
@(Html.Kendo().DatePicker()
                .Name("Date")
                .Value(Model == null ? DateTime.Now : Model.Date)
                .Format("d/M/yyyy")
)

  • I tried adding the DatePicker by selecting the class "dateControl" and using the "dateTemplate" at the bottom, as I found in some example, but it didn't work.
  • I also tried creating a standard jQuery date picker in the "datepicker" input, but it only works outside the grid, not in the template. This is why I noticed my jQuery selectors were not working.
  • The first column will have a star image and it will be used to tag/untag the product as favorite, so it will need some jQuery attached.
  • The plus sign in the last column adds the product to the shopping cart, so it will need some jQuery attached as well.
  • Regarding the style, I also tried setting the borders in order to make both lines look as one, but it seems my styles are getting overridden by Kendo's CSS, I guess. The way I was able to do it was by playing with the background gradients in classes line1 and line2, which doesn't look like the best option, but I was too worried about the calendar to try to optimize this.
I hope it is not too much to ask two more questions:
  • Could I do this using the server "RowTemplate" method instead? Yet again, I tried but couldn't do it.
  • For the sake of tidiness, can I place the template in a tag like <script id="rowTemplate" type="text/x-kendo-tmpl"> and then reference it from the ClientRowTemplate line?
I'm using current Kendo UI version 2013.2.918, MVC version with Razor in Visual Studio 2012.
Windows 7 Professional and IE10 (sorry, my client uses this!).

Really thanks a lot for reading my whole post. I've spent countless hours trying to do all this without much success.

Andrew
Atanas Korchev
Telerik team
 answered on 21 Oct 2013
3 answers
1.3K+ views
Hello,
i'm new to KendoGrid and this is my first Project. I hope you can help me and forgive my bad english ;)

The Problem:
If I bind another Object to a Column which is included in the Object of the Row, sorting and filtering doesn't work anymore.
Each Row, I bind a "Adress" Object, include a "Country" Object. I use a ClientTemplate to show the "Description" Property (if not null).
I know that a ClientTemplate breaks the Sorting and Filtering, but i don't know how to solve this by the MVC Wrapper. I found no examples.

In Inline-Editormode I display for the Country-Object a Kendo-DropDownList for valid values. This works fine for CRUD.
For the Country Column in Read-Mode I've added a Custom Filter with a Kendo-DropdownList for the valid values, but there is a empty DropDownList for the Filter-Options (for ex. "ss equal to"...). So if i press "Filter" or sorting the Column, the Grid don't know how to sort/filter.

PS.: The Country is attached/connected by the EntityFramework(Designer) and the Models were created automatically.

The Question:
How can i solve my Problem? How can i implement with the MVC Wrapper a working sorting/filtering for an Object in a Column? And.... is there a better solution to bind a Object to a Column with a DropDownList?

Thank you for your help :)

Grid View
@{
    Layout = "~/Views/Shared/Layout.cshtml";
}
 
@model IEnumerable<LiCPSAdmin2.Models.Adressen>
 
@(Html.Kendo().Grid(Model)
    .Name("Adressen")
    .Columns(columns =>
    {
        columns.Command(command =>
        {
            command.Edit().Text(" ");
            command.Destroy().Text(" ");
        }).Width(90).HtmlAttributes(new { style = "background-color: rgb(238, 238, 238)" });
        columns.Bound(p => p.Eadr).Title("Adresse").Width(90).HtmlAttributes(new { style = "text-align:center;" });
        columns.Bound(p => p.Nama).Title("Name").Width(200);
        columns.Bound(p => p.Namb).Title("Name 2").Width(200);
        columns.Bound(p => p.Namc).Title("Strasse");
        columns.Bound(p => p.Namd).Title("Strasse 2");
        columns.Bound(p => p.Name).Title("Plz, Ort");
        columns.Bound(p => p.Namf).Title("Ort 2");
        columns.Bound(p => p.Pstc).Title("PLZ").Width(90).HtmlAttributes(new { style = "text-align:center;" });
        columns.Bound(p => p.Ccty).Title("Land").Width(90).HtmlAttributes(new { style = "text-align:center;" });
        columns.Bound(p => p.BaLand).Title("Bezeichnung").Width(200).ClientTemplate(" #= BaLand ? BaLand.Dsca : '' # ").Filterable(filter => filter.UI("BaLandFilter"));
    })
    .DataSource(dataSource => dataSource
        .Ajax()
        .PageSize(50)
        .Model(model =>
        {
            model.Id(p => p.Eadr);
            model.Field(p => p.Eadr).Editable(false);
        })
        .Events(events => events.Error("error_handler"))
        .Create(create => create.Action("Create", "Adressen"))
        .Read(read => read.Action("Read", "Adressen"))
        .Update(update => update.Action("Edit", "Adressen"))
        .Destroy(destroy => destroy.Action("Delete", "Adressen"))
    )
    .Events(events => events.Edit("edit_handler"))
    .ToolBar(toolbar => toolbar.Create())
    .Editable(editable => editable.Mode(GridEditMode.InLine))
    .Sortable(sortable => sortable.AllowUnsort(true).SortMode(GridSortMode.MultipleColumn))
    .Filterable(filter => filter.Extra(false))
    .ColumnResizeHandleWidth(5)
    .Scrollable(scrollable => scrollable.Virtual(true))
    .HtmlAttributes(new { style = "height:100%;" })
    .Navigatable(nav => nav.Enabled(true))
    .Resizable(resize => resize.Columns(true))
    .Reorderable(reordering => reordering.Columns(true))
    .Pageable()
)
 
<script type="text/javascript">
 
    function error_handler(e) {
        if (e.errors) {
            var message = "Errors:\n";
            $.each(e.errors, function (key, value) {
                if ('errors' in value) {
                    $.each(value.errors, function () {
                        message += this + "\n";
                    });
                }
            });
            alert(message);
            var grid = $("#Adressen").data("kendoGrid");
            grid.cancelChanges();
        }
    };
 
    function baland_change() {
        $("#Ccty").val(this.value()).css({ 'background-color': '#fff' }).trigger("change");
    }
 
    function edit_handler(e) {
        $(".k-grid-update").html("<span class=\"k-icon k-update\"></span>");
        $(".k-grid-cancel").html("<span class=\"k-icon k-cancel\"></span>");
 
        e.container.find("#Ccty").focusout(function () {
            e.container.find("#BaLand").data("kendoDropDownList").value($(this).val());
        });
    }
 
    function BaLandFilter(element) {
        element.kendoDropDownList({
            dataSource: {
                transport: {
                    read: "@Url.Action("FilterMenuCustomization_BaLand")"
                }
            },
            optionLabel: "Bitte wählen"
        });
    }
 
</script>
Editor Template for Countries (BaLand)
@(Html.Kendo().DropDownList()
    .Name("BaLand")
    .BindTo((System.Collections.IEnumerable)TempData["Land"])
    .DataTextField("Dsca")
    .DataValueField("Ccty")
    .OptionLabel("Bitte wählen")
    .Events(e => e
        .Change("baland_change")
    )
)

Adress Controller

public class AdressenController : Controller
    {
        private LiCPS_Develop_V20Entities db = new LiCPS_Develop_V20Entities();
 
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
 
        // Index
        public ActionResult Index()
        {
            TempData["Land"] = db.BaLand.ToList();
            var adressen = db.Adressen.Include(a => a.BaLand).Distinct();
            return View(adressen.ToList());
        }
 
        public ActionResult FilterMenuCustomization_BaLand()
        {
            return Json(db.BaLand.Select(e => e.Dsca).Distinct(), JsonRequestBehavior.AllowGet);
        }
 
        // Grid
        public ActionResult Read([DataSourceRequest] DataSourceRequest request)
        {
            return Json(((db.Adressen.Include(a => a.BaLand).Distinct()).ToList()).ToDataSourceResult(request));
        }
 
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create([DataSourceRequest] DataSourceRequest request, Adressen adressen)
        {
            if (adressen != null && ModelState.IsValid)
            {
                adressen.Eadr = Convert.ToInt32(HelperFunctions.getNextNumber(10, 2));
                db.Adressen.Add(adressen);
                db.Entry(adressen.BaLand).State = EntityState.Unchanged;
                
                try
                {
                    db.SaveChanges();
                }
                catch (InvalidOperationException ex)
                {
                    ModelState.AddModelError(string.Empty, "Es ist ein Fehler aufgetreten! Der Datensatz wurde nicht erstellt");
                }
                catch (DbEntityValidationException ex)
                {
                    ModelState.AddModelError(string.Empty, "Es ist ein Fehler aufgetreten! Der Datensatz wurde nicht erstellt");
                }
                catch (DbUpdateException ex)
                {
                    ModelState.AddModelError(string.Empty, "Es ist ein Fehler aufgetreten! Die Adress-Nummer ist bereits vergeben.");
                }              
            }
 
            return Json(new[] { adressen }.ToDataSourceResult(request, ModelState));
        }
 
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete([DataSourceRequest] DataSourceRequest request, Adressen adressen)
        {
            Adressen Adressen = null;
 
            if (ModelState.IsValid)
            {
                Adressen = db.Adressen.Find(adressen.Eadr);
                db.Adressen.Remove(Adressen);
                db.SaveChanges();
            }
 
            return Json(new[] { adressen }.ToDataSourceResult(request, ModelState));
        }
 
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit([DataSourceRequest] DataSourceRequest request, Adressen adressen)
        {
            if (adressen != null && ModelState.IsValid)
            {
                db.Entry(adressen).State = EntityState.Modified;
                db.Entry(adressen.BaLand).State = EntityState.Unchanged;
 
                try
                {
                    db.SaveChanges();
                }
                catch (InvalidOperationException ex)
                {
                    ModelState.AddModelError(string.Empty, "Es ist ein Fehler aufgetreten! Der Datensatz wurde nicht gespeichert");
                }
                catch (DbEntityValidationException ex)
                {
                    ModelState.AddModelError(string.Empty, "Es ist ein Fehler aufgetreten! Der Datensatz wurde nicht gespeichert");
                }
                catch (DbUpdateException ex)
                {
                    ModelState.AddModelError(string.Empty, "Es ist ein Fehler aufgetreten! Der Datensatz wurde nicht gespeichert");
                }   
            }
             
            return Json(new[] { adressen }.ToDataSourceResult(request, ModelState));
        }    
    }
Model for Adress
public partial class Adressen
    {
        public int Eadr { get; set; }
        public string Nama { get; set; }
        public string Namb { get; set; }
        public string Namc { get; set; }
        public string Namd { get; set; }
        public string Name { get; set; }
        public string Namf { get; set; }
        public string Pstc { get; set; }
        public string Ccty { get; set; }
 
        public virtual BaLand BaLand { get; set; }
    }
Model for Countries
public partial class BaLand
{
    public string Ccty { get; set; }
    public string Dsca { get; set; }
    public string Ictc { get; set; }
    public Nullable<short> Meec { get; set; }
    public string Tfcd { get; set; }
}
Helga
Top achievements
Rank 1
 answered on 21 Oct 2013
3 answers
615 views
Am new to to Kendo.mvc
Inherited a MVC app that make use of a Kendo Grid that seems to be making calls to a controller methods (returns list).
When Debugging in VS2010 I can cannot hit break points that I am setting in the controller, is that because I am going out of process through the Kendo.MVC DLL ?

I would welcome any tips about debugging Kendo in general.
Atanas Korchev
Telerik team
 answered on 21 Oct 2013
1 answer
105 views
I am not able to bind a dropdown in a grid which is in a tabstrip. I followed the foriegn key demo but didn't work. I also tried binding dropdown to hard coded vaule but no luck. Below is the code of my view:

items.Add().Text("Charges").Content(@<text>
<h1>Hauling Charges</h1>
@(Html.Kendo().Grid<IAAI.ASAP.DomainModel.Operations.Dispatch.TowCharge>()
.Name("chargeGrid")
.Columns(columns =>
{
//columns.Bound(p => p.ChargeType).ClientTemplate("#=ChargeTypes.Charge_Description#").Title("Charge Type").Width(110); //.EditorTemplateName("testNew").Width(160);//Title("Charge Type").Width(110);//.EditorTemplateName("ChargeType");
// columns.Bound(p => p.ChargeType).EditorTemplateName("testNew").ClientTemplate("#=ChargeType.Charge_ID#");
columns.Bound(p => p.Amount).Title("Amount").Width(110);
columns.Bound(p => p.ResponsibleParty).Title("Responsible").Width(150);
//columns.ForeignKey(p => p.Charge_ID, (IEnumerable<IAAI.ASAP.DomainModel.Operations.Dispatch.ChargeType>)ViewBag.ChargeType, "Charge_ID", "Charge_Description")
// .Title("Charge Test").Width(150);
columns.ForeignKey(c => c.Charge_ID, new SelectList(new[]{
new {text="t1",value = "1"},
new {text="t2",value = "2"},
new {text="t3",value = "3"},
}, "value", "text")).Title("Charge New");
// columns.ForeignKey(p => p.Charge_ID, (System.Collections.IEnumerable)ViewBag.ChargeType, "Charge_ID", "Charge_Description").HtmlAttributes(new { id = "Charge_ID" }).Title("Charge New");
columns.Command(command => command.Destroy()).Width(110);
columns.Command(command => command.Edit()).Width(200);

})

.Editable(editable => editable.Mode(GridEditMode.PopUp))
.Pageable()
.Sortable()
.DataSource(datasource => datasource
.Ajax()
.Model(model =>
{
model.Id(p => p.Charge_ID);
// model.Field(p => p.Charge_ID).Editable(false);
//// model.Field(p => p.Charge_ID).DefaultValue(1);
model.Field(p => p.ChargeTypes).DefaultValue(
ViewBag.ChargeType as IEnumerable<IAAI.ASAP.DomainModel.Operations.Dispatch.ChargeType>);
})

.Read(read => read.Action("ChargesRead", "Dispatch", new { salvageID = "#=SalvageID#", towbill="#=TowBillNumber#", towChargeType="Hauling" }))
.Update(update => update.Action("ChargeTypes_Update", "Dispatch"))
.Destroy(destroy => destroy.Action("ChargeTypes_Destroy", "Dispatch"))
)
.ToClientTemplate()
)


</text>
Daniel
Telerik team
 answered on 18 Oct 2013
3 answers
1.3K+ views
Hi,

I have the kendoui.aspnetmvc.2013.2.918 version, so I want to know if it is possible to populate the Upload control with a previously uploaded file and be able to remove the file if I want.
If it is not supported now, are you planning to add this functionality in a new release ?

Thanks in advance.
Dimiter Madjarov
Telerik team
 answered on 18 Oct 2013
0 answers
62 views
This demo shows the DropDownLists vertically:
http://demos.kendoui.com/web/dropdownlist/cascadingdropdownlist.html
Can i change this to horizontal?
Daniel
Top achievements
Rank 1
 asked on 18 Oct 2013
2 answers
372 views
I have a pure JS grid I was using with an asp.net forms backend (.ashx). It has been working fine for six months. I am trying to convert it to an MVC controller for the backend now, but having no luck:

function MaterialsGrid(ticket_ID, grid_id, is_editable, default_billable) {
    var self = this;
    self.ticket_ID = ticket_ID;
    self.GRID_ID = '#' + grid_id;
    self.HANDLER_URL = "/MaterialEntry";
    self.IS_EDITABLE = is_editable;
    self.DEFAULT_BILLABLE = default_billable;
 
    self.material_source = new kendo.data.DataSource({
        batch: true,
        schema: {
            model: {
                id: "MaterialEntryID",
                fields: {
                    MaterialEntryID: { type: "string" },
                    TicketID: { type: "string" },
 
                    ItemID: { type: "number", defaultValue: 0 },
                    ItemName: { type: "string", defaultValue: GridCommon.emptyText },
 
                    Description: { type: "string" },
 
                    Quantity: { type: "number", defaultValue: 0, validation: { required: true, min: 0 } },
 
                    Rate: { type: "number", defaultValue: 0 },
                    Total: { type: "number", defaultValue: 0 },
                     
                    Billable: { type: "boolean", defaultValue: self.DEFAULT_BILLABLE },
                },
            }
        },
 
        transport: {
            read: {
                url: self.HANDLER_URL + "/Read",
                dataType: "json",
                type: "GET",
                cache: false,
            },
            update: {
                url: self.HANDLER_URL + "/Update",
                dataType: "json",
                type: "PUT",
            },
            destroy: {
                url: self.HANDLER_URL + "/Destroy",
                dataType: "json",
                type: "POST",
            },
            create: {
                url: self.HANDLER_URL + "/Create",
                dataType: "json",
                type: "POST",
            },
 
            parameterMap: function (options, operation) {
                if (operation === "read") {
                    return { ticketID: self.ticket_ID };
                }
 
                if (operation === "read") {
                    return { ticketID: self.ticket_ID };
                } else if (options.models) {
                    return { materials: kendo.stringify(options.models), ticketID: self.ticket_ID };
                }
            }
        },
 
        error: GridCommon.showCallBackError
    });
 
    self.items_src = new kendo.data.DataSource({
        transport: {
            read: {
                url: self.HANDLER_URL + "/GetItems",
                dataType: "json",
                type: "GET"
            }
        },
        error: GridCommon.showCallBackError
    });
 
    self.itemDropDownEditor = function (container, options) {
 
        $('<input required data-text-field="ExtendedItemName" data-value-field="ItemName" data-bind="value:' + options.field + '"/>')
            .appendTo(container)
            .kendoDropDownList({
                autoBind: false,
                optionLabel: { ExtendedItemName: GridCommon.emptyText, ItemID: 0 },
                dataSource: self.items_src,
                change: function (e) {
                    options.model.set('ItemID', e.sender.dataItem().ItemID);
                }
            });
    }
 
    self.updateTotal = function (e) {
        var r = e.values.Rate ? e.values.Rate : e.model.Rate;
        var q = e.values.Quantity ? e.values.Quantity : e.model.Quantity;
        e.model.set('Total', q * r);
    }
 
    self.init = function () {
 
        var tools = null;
        var row_commands = null;
        if (self.IS_EDITABLE) {
            tools = [
                { name: "save", text: "Save" },
                { name: "cancel", text: "Cancel" },
                { name: "create", text: "Add" },
                { template: GridCommon.toggleBillableTemplate(self.GRID_ID) }
            ];
            row_commands = [{
                name: "destroy",
                template: '<a href="##" class="k-grid-delete"><img img src="/Content/images/icons/delete.png" /></a>'
            }]
        } else {
            $(self.GRID_ID).addClass('readonly');
        }
        $(self.GRID_ID).kendoGrid({
            toolbar: tools,
 
            save: self.updateTotal,
 
            columns: [
                { field: "ItemName", title: "Item Type", editor: self.itemDropDownEditor },
                { field: "Description" },
                { field: "Quantity", title: "QTY", width: 65, editor: GridCommon.numberEditor },
                { field: "Rate", title: "Price", format: "{0:c}", width: 90, editor: GridCommon.numberEditor },
                { field: "Total", editor: GridCommon.notEditable, format: "{0:c}", width: 95 },
                { field: "Billable", template: '#= GridCommon.getBillableText(Billable) #', width: 100},
                { command: row_commands, width: 40 }
            ],
 
            pageable: false,
            scrollable: true,
            editable: self.IS_EDITABLE,
            navigatable: true,
            sortable: true,
            batch: true,
 
            dataSource: self.material_source,
            saveChanges: GridCommon.saveAll
        });
    }
}

@model Guid
 
<div class="grid-wrapper">
    <div id="materials-data" class="grid-global-save">
        <!-- grid will appear here -->
    </div>
</div>
<script type="text/javascript">
    var mat_grid = new MaterialsGrid('@Model', 'materials-data', true, true);
    $(document).ready(mat_grid.init);
</script>
My material entry controller for the Create function looks like this:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult Create([DataSourceRequest] DataSourceRequest request, IEnumerable<TempVM> materials, string ticketId)
{
    ModelState.Remove("MaterialEntryId");
    ModelState.Remove("Id");
 
    return Json("");
}
public class TempVM
{
    public string MaterialEntryID { get; set; }
    public string TicketID { get; set; }
    public int ItemID { get; set; }
    public string Description { get; set; }
 
}

I know the logic inside create isn't right. But the problem is that the 'materials' parameter is empty when the Create method is called. You can see that the form data seems to be being sent correctly in chrome's Netowork tab, by looking at the attached file.

Any ideas what I am doing wrong?
Petur Subev
Telerik team
 answered on 17 Oct 2013
3 answers
375 views
Hello,
I'm trying to use an MVC-grid with a custom edit template. I think I got most of it working, but I have a strange problem. The validationmessages ends up in a weird position. The middle message ends up under the dropdown, even though the first one end up on top of another dropdown. Is there a possibility to control the z-level? I don't even set the ValidationMessageFor for the dropdowns, but I guess they are automatic since I have an OptionLabel on them. 

@Html.HiddenFor(model => model.Id)
 
<div class="editor-label">
    @Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.Name)
    @Html.ValidationMessageFor(model => model.Name)
</div>
 
<div class="editor-label">
    @Html.LabelFor(model => model.OwnerId)
</div>
<div class="editor-field">
     
  @(Html.Kendo().DropDownList()
          .Name("OwnerId")
          .HtmlAttributes(new { style = "width: 250px" })
           .DataTextField("NamePlusDepartment")
          .DataValueField("Id")
          .OptionLabel("Välj en person")
          .DataValueField("Id")         
          .DataSource(source => {
              source.Read(read =>
              {
                  read.Action("GetPersonal", "List");
              });
          })                  
    )
 
     
</div>
<div class="editor-label">
    @Html.LabelFor(model => model.ResponsibleId)
</div>
<div class="editor-field">
     
  @(Html.Kendo().DropDownList()
          .Name("ResponsibleId")
          .HtmlAttributes(new { style = "width: 250px" })
           .DataTextField("NamePlusDepartment")
          .DataValueField("Id")
          .OptionLabel("Välj en person")
          .DataSource(source => {
              source.Read(read =>
              {
                  read.Action("GetPersonal", "List");
              });
          })                   
    )
 
     
</div>
Kiril Nikolov
Telerik team
 answered on 17 Oct 2013
2 answers
1.4K+ views
Hello -

I had to change my Model to include two lists so i can bind it to two sets.

Now my model looks like:
public class PaymentsViewModel
{
    public List<CorporateViewModel> Corporations { get; set; }
    public List<PaymentViewModel> Payments { get; set; }
}
My controller looks like
public ActionResult Payments_Read([DataSourceRequest]DataSourceRequest request)
{
    //get corps
    //get payments
 
    PaymentsViewModel returnObj = new PaymentsViewModel();
    returnObj.Corporations = corps;
    returnObj.Payments = payments;
 
    DataSourceResult result = returnObj.ToDataSourceResult(request); <== returns error
 
    return Json(result);
}

Errors:
  • cannot convert from 'PaymentsViewModel' to 'System.Data.DataTable' 
  • 'PaymentsViewModel' does not contain a definition for 'ToDataSourceResult' and the best extension method overload 'Kendo.Mvc.Extensions.QueryableExtensions.ToDataSourceResult(System.Data.DataTable, Kendo.Mvc.UI.DataSourceRequest)' has some invalid arguments 
Any  ideas how to go about it? Should I change my ViewModel? Or have different approach?

Thanks.
Christos
Top achievements
Rank 1
 answered on 16 Oct 2013
Narrow your results
Selected tags
Tags
+? more
Top users last month
Will
Top achievements
Rank 2
Iron
Motti
Top achievements
Rank 1
Iron
Hester
Top achievements
Rank 1
Iron
Bob
Top achievements
Rank 3
Iron
Iron
Veteran
Thomas
Top achievements
Rank 2
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Will
Top achievements
Rank 2
Iron
Motti
Top achievements
Rank 1
Iron
Hester
Top achievements
Rank 1
Iron
Bob
Top achievements
Rank 3
Iron
Iron
Veteran
Thomas
Top achievements
Rank 2
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?