简体   繁体   中英

kendo ui grid with dropdownlist

i am using dropdownlist inside the kendo ui ajax grid using asp.net mvc i am using change method of dropdownlsit because one of the grid column is bind with the dropdownlist but when i am setting the value i am getting [object object] can anyone help me out thanks

<%: Html.Kendo().Grid<SSTS.Models.FaresBasedViewModel>()
.Name("grid2")
      .Columns(columns =>
      {
           columns.ForeignKey(p => p.StudentNumber, (System.Collections.IEnumerable)ViewData["students"], "StudentNumber", "StudentNumber")
        .Title("StudentNumber").Width(150);    
          columns.Bound(student => student.GivenName).Width(150);      
          columns.Bound(student => student.DateGovernmentFunded).Width(150);
          columns.Bound(student => student.SectionNumber).Width(150); ;
          columns.Bound(student => student.Description).Width(150);
          columns.Bound(student => student.Distance).Width(150);
          columns.Bound(student => student.FareNumber).Width(150); 
          columns.Bound(student => student.FareType).Width(150); 
          columns.Bound(student => student.TopeUpCode).Width(150);
          columns.Bound(student => student.ApplicationID).Width(150); 

          columns.Command(commands =>
          {
              commands.Edit(); 
              commands.Destroy(); 
          }).Title("Commands").Width(150);
      })
      .ToolBar(toolbar => toolbar.Create()) 
      .Editable(editable => editable.Mode(GridEditMode.InLine))
      .DataSource(dataSource =>
          dataSource.Ajax()
         .Events(events => events.Change("change"))
            .Model(model =>
            {
                model.Id(student => student.FareBaseID); 
                model.Field(p => p.StudentNumber).DefaultValue("");   

            })
           .Create(create => create.Action("FaresBased_Create", "ServiceUse"))  
           .Read(read => read.Action("FaresBased_Read", "ServiceUse")) 
           .Update(update => update.Action("FaresBased_Update", "ServiceUse")) 
           .Destroy(destroy => destroy.Action("FaresBased_Destroy", "ServiceUse")) 
        )
          .Pageable().Scrollable()
%>



    function change(e) {
        if (e.field == "StudentNumber") {
            var model = e.items[0];

            model.set("GivenName", model);

        }
    }

你应该使用设置在您的DropDownList的价值selectvalue利用作为参数的idDropDownList

Here's an example of how I am using a DropDownList to filter a Grid.

@{
    ViewBag.Title = "Contacts";
    var customerId = ViewContext.RouteData.Values["id"];
}

<h2>@ViewBag.Title</h2>

@(
Html.Kendo()
    .Grid<Fss.Areas.Customers.Models.Contact>()
    .Name("contacts")
    .Columns(columns =>
    {
        columns.Bound(c => c.Active).ClientTemplate("<input type=\"checkbox\" disabled=\"disabled\" value=\"#= ContactId #\" # if (Active) { #checked='checked'# } #/>");
        columns.Bound(c => c.LastName);
        columns.Bound(c => c.FirstName);
        columns.Bound(c => c.Email);
        columns.Bound(c => c.Phone);
        columns.Bound(c => c.Mobile);
        columns.Bound(c => c.Changed).Format("{0:HH:mm:ss d/M/yyyy}");
        columns.Bound(c => c.ChangedBy);
        columns.Command(command =>
        {
            command.Edit();
            command.Destroy();
        }).Width(172);
    })
    .ToolBar(toolbar =>
    {
        toolbar.Template(@<text>
            @item.CreateButton()
            <div class="toolbar">
            @Html.Label("Customer", new { @class = "customer-label" })
            @(Html.Kendo()
                  .DropDownList()
                  .Name("customers")
                  .DataTextField("Name")
                  .DataValueField("CustomerId")
                  .AutoBind(true)
                  .Events(e => e.Change("changeCustomer"))
                  .Value(customerId.ToString())
                  .DataSource(source => source.Read(read => read.Action("GetCustomers", "Contacts")))
            )
            </div>
            </text>);
    })
    .Editable(editable => editable.Mode(GridEditMode.PopUp))
    .Pageable(pageable => pageable.ButtonCount(5))
    .Sortable(sortable => sortable.AllowUnsort(true).SortMode(GridSortMode.MultipleColumn))
    .Scrollable()
    .Filterable()
    .Reorderable(con => con.Columns(true))
    .Resizable(con => con.Columns(true))
    .ColumnResizeHandleWidth(5)
    .HtmlAttributes(new { style = "height:600px;" })
    .Events(e => e.Edit("edit"))
    .DataSource(dataSource => dataSource.Ajax()
                                        .PageSize(10)
                                        .Events(events => events.Error("error_handler"))
                                        .Model(model =>
                                        {
                                            model.Id(c => c.ContactId);
                                            model.Field(f => f.CustomerId).Editable(false);
                                            model.Field(f => f.Changed).Editable(false);
                                            model.Field(f => f.ChangedBy).Editable(false);
                                            model.Field(f => f.Error).Editable(false);
                                        })
                                        .Filter(filter => filter.Add(c => c.CustomerId.ToString() == customerId.ToString()))
                                        .Create(c => c.Action("Create", "Contacts").Data("getCustomerId"))
                                        .Read(r => r.Action("Read", "Contacts"))
                                        .Update(u => u.Action("Edit", "Contacts"))
                                        .Destroy(d => d.Action("Delete", "Contacts")))
)

<style scoped="scoped">    
    #contacts .k-toolbar
    {
        min-height: 27px;
        padding: 1.3em;
    }

    .customer-label
    {
        vertical-align: middle;
        padding-right: .5em;
    }

    .toolbar
    {
        float: right;
    }
</style>
<script type="text/javascript">
    function getCustomerId() {
        return {id:$("#customers").val()};
    }
    function changeCustomer(e) {
        var value = this.value(), grid = $("#contacts").data("kendoGrid");

        if (value) {
            grid.dataSource.filter({ field: "CustomerId", operator: "eq", value: parseInt(value) });
        }
        else {
            grid.dataSource.filter({});
        }
    }
    function edit(e) {        
        $.each(["Changed", "ChangedBy", "Error", "ContactId", "CustomerId"], function (index, value) {
            e.container.find("label[for='" + value + "']").parent().attr("style", "display:none;");
            e.container.find("input[name='" + value + "']").parent().attr("style", "display:none;");
        });
    }
</script>
@Scripts.Render("~/bundles/editing")

This is the controller code:

using AutoMapper;
using Fss.Areas.Customers.Models;
using Fss.Models;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using System;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;

namespace Fss.Areas.Customers.Controllers
{
    public class ContactsController : Controller
    {
        FssData.EntitiesModel _DbContext;

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create([DataSourceRequest]
                                   DataSourceRequest request, Contact contact, int id)
        {
            if (contact != null && this.ModelState.IsValid)
            {
                var currentDateTime = this._DbContext.GetDateTime();
                var customer = this._DbContext.Customers.FirstOrDefault(c => c.CustomerId == id);

                if (customer != null)
                {
                    var dataContact = Mapper.Map(contact, new FssData.Contact());
                    dataContact.CustomerId = customer.CustomerId;
                    dataContact.SyncId = Guid.NewGuid();
                    dataContact.Created = currentDateTime;
                    dataContact.CreatedBy = this.User.Identity.Name;
                    dataContact.Changed = currentDateTime;
                    dataContact.ChangedBy = this.User.Identity.Name;
                    this._DbContext.Add(dataContact);
                    this._DbContext.SaveChanges();
                    Mapper.Map(dataContact, contact);
                }
            }

            return this.Json(new[]
                             {
                                 contact
                             }.ToDataSourceResult(request, this.ModelState));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete([DataSourceRequest]
                                   DataSourceRequest request, Contact contact)
        {
            if (contact != null && this.ModelState.IsValid)
            {
                var dataContact = this._DbContext.Contacts.FirstOrDefault(c => c.ContactId.Equals(contact.ContactId));
                if (dataContact != null)
                {
                    this._DbContext.Delete(dataContact);
                    this._DbContext.SaveChanges();
                }
            }

            return this.Json(new[]
                             {
                                 contact
                             }.ToDataSourceResult(request, this.ModelState));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit([DataSourceRequest]
                                 DataSourceRequest request, Contact contact)
        {
            if (contact != null && this.ModelState.IsValid)
            {
                var currentDateTime = this._DbContext.GetDateTime();
                var dataContact = this._DbContext.Contacts.FirstOrDefault(c => c.ContactId.Equals(contact.ContactId));

                if (dataContact != null)
                {
                    Mapper.Map(contact, dataContact);

                    dataContact.Changed = currentDateTime;
                    dataContact.ChangedBy = this.User.Identity.Name;

                    this._DbContext.SaveChanges();

                    Mapper.Map(dataContact, contact);
                }
            }
            return this.Json(new[]
                             {
                                 contact
                             }.ToDataSourceResult(request, this.ModelState));
        }

        public ActionResult Customer(int id)
        {
            return this.View();
        }

        public ActionResult GetCustomers()
        {
            return this.Json(this._DbContext.Customers.Select(c => new { Name = c.Name, CustomerId = c.CustomerId }), JsonRequestBehavior.AllowGet);
        }

        public ActionResult Index()
        {
            var customer = this._DbContext.Customers.FirstOrDefault();
            return this.RedirectToAction(actionName: "Customer", routeValues: new { id = customer != null ? customer.CustomerId : 0 });
        }

        public ActionResult Read([DataSourceRequest]
                                 DataSourceRequest request)
        {
            return this.Json(this._DbContext.Contacts.Select(c => Mapper.Map<Contact>(c)).ToDataSourceResult(request));
        }

        protected override void Initialize(RequestContext requestContext)
        {
            this._DbContext = ContextFactory.GetContextPerRequest();
            base.Initialize(requestContext);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM