具有多选列SCRlueT5007的Kendo mvc网格:无法获取未定义或空引用的属性“set”

时间:2018-02-19 19:08:01

标签: jquery asp.net-mvc kendo-grid kendo-asp.net-mvc kendo-multiselect

起初我想为我糟糕的英语道歉。 因此,我有两个模型,其中包含“多对多”,书籍,作者及其上下文库。正确包含所有源文件,不知道为什么我的代码不起作用。

标题中描述了我的问题。我希望你的帮助)。 所有代码都在下面(你不必阅读所有代码,我认为我的javascript中的问题,因为我的javascript技能非常糟糕)。 当我尝试连续设置所选作者时发生错误 in this moment

这里的Index.cshtml文件中的问题:(在更改功能中)

<script type="text/javascript">
    function dataBound(e) {
        var grid = this;
        grid.tbody.children().each(function () {
            var dataitem = grid.dataItem(this),
                row = $(this);
            eval(row.find("script").html());
            var multiSelect = $(this).find("select").data("kendoMultiSelect");
            multiSelect.value(dataitem.Authors.map(function (i) { return i.AuthorId }));
        });
    }

    function change(e) {
        var row = this.element.closest("tr"),
            **//problem is here**
            model = $("#grid").data("kendoGrid").dataItem(row);
        model.set("Authors", this.dataItems());
    }
    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);
        }
    }
</script>
@(Html.Kendo().Grid<ManyToMany.Models.ViewModel>()
                .Name("grid")
                .Columns(columns =>
                {
                    columns.Bound(e => e.BookId).Visible(false);
                    columns.Bound(e => e.Pages);
                    columns.Bound(e => e.Genre);
                    columns.Bound(e => e.Publisher);
                    columns.Bound(e => e.Authors).ClientTemplate(

                         Html.Kendo().MultiSelect().Name("multi#=BookId#")
                            .DataTextField("AuthorName")
                            .DataValueField("AuthorId")
                            .BindTo((IEnumerable<ManyToMany.Models.Author>)ViewData["authors"]) /*TaskSecond.Models.ViewModel*/
                            .Events(e => e.Change("change"))
                            .ToClientTemplate().ToHtmlString()
                        );
                    columns.Command(command => command.Destroy()).Width(150);

                })
                .ToolBar(toolbar =>
                {
                    toolbar.Create();
                    toolbar.Save();
                })
                .Editable(editable => editable.Mode(GridEditMode.InCell))
                                                    .Pageable()
                                                    .Filterable()
                .Events(e => e.DataBound("dataBound"))
                .DataSource(dataSource => dataSource
                    .Ajax()
                    .Batch(true)
                .Model(model =>
                {
                    model.Id(p => p.BookId);
                    model.Field(p => p.Pages).DefaultValue(0);
                    model.Field(p => p.Genre).DefaultValue(0);
                    model.Field(p => p.Publisher).DefaultValue("");
                    model.Field(p => p.Authors).DefaultValue(
                        ViewData["defaultAuthors"] as ManyToMany.Models.Author);
                })
                    .PageSize(5)
                     .Read(read => read.Action("Books_Read", "Grid"))
        .Create(create => create.Action("Books_Create", "Grid"))
         .Update(update => update.Action("Books_Update", "Grid"))
        .Destroy(destroy => destroy.Action("Books_Destroy", "Grid"))
                    .ServerOperation(false))
)
//////////////////////////////////////////////////////////////////
//defaultAuthors.cshtml
@model IEnumerable<ManyToMany.Models.ViewModel>

@(
                Html.Kendo().MultiSelectFor(m => m)
                    .DataTextField("AuthorName")
                    .DataValueField("AuthorId")
                    .BindTo((IEnumerable<ManyToMany.Models.ViewModel>)ViewData["authors"])
)

我的控制器:

public class GridController : Controller

{         私人图书馆db = new Library();

    public ActionResult Index()
    {
        var temp = db.Authors.FirstOrDefault();
        List<Author> author = new List<Author>();
        author.Add(temp);
        ViewData["defaultAuthors"] = author;
        ViewData["authors"] = db.Authors;            
        return View();
    }

    public ActionResult Books_Read([DataSourceRequest]DataSourceRequest request)
    {
        IQueryable<Book> books = db.Books;
        DataSourceResult result = books.ToDataSourceResult(request, c => new ViewModel
        {
            BookId = c.BookId,
            BookName = c.BookName,
            Pages = c.Pages,
            Genre = c.Genre,
            Publisher = c.Publisher,
            Authors = new List<Author>(c.Authors)
        });

        return Json(result, JsonRequestBehavior.AllowGet);
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Books_Create([DataSourceRequest]DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<ViewModel> books)
    {
        var entities = new List<Book>();
        if (books != null && ModelState.IsValid)
        {
            foreach (var book in books)
            {
                var entity = new Book
                {
                    BookName = book.BookName,
                    Pages = book.Pages,
                    Genre = book.Genre,
                    Publisher = book.Publisher,
                    Authors = new List<Author>(book.Authors)
                };

                db.Books.Add(entity);
                entities.Add(entity);
            }
            db.SaveChanges();
        }

        return Json(entities.ToDataSourceResult(request, ModelState, book => new ViewModel
        {
            BookName = book.BookName,
            Pages = book.Pages,
            Genre = book.Genre,
            Publisher = book.Publisher,
            Authors = new List<Author>(book.Authors)
        }));
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Books_Update([DataSourceRequest]DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<ViewModel> books)
    {

        var entities = new List<Book>();
        if (books != null && ModelState.IsValid)
        {
            foreach (var book in books)
            {
                var entity = new Book
                {
                    BookId = book.BookId,
                    BookName = book.BookName,
                    Pages = book.Pages,
                    Genre = book.Genre,
                    Publisher = book.Publisher,
                    Authors = new List<Author>(book.Authors)
                };

                entities.Add(entity);
                db.Books.Attach(entity);
                db.Entry(entity).State = EntityState.Modified;
            }
            db.SaveChanges();

        }

        return Json(entities.ToDataSourceResult(request, ModelState, book => new ViewModel
        {
            BookName = book.BookName,
            Pages = book.Pages,
            Genre = book.Genre,
            Publisher = book.Publisher,
            Authors = new List<Author>(book.Authors)
        }));
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Books_Destroy([DataSourceRequest]DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<ViewModel> books)
    {
        var entities = new List<Book>();
        if (ModelState.IsValid)
        {
            foreach (var book in books)
            {
                var entity = new Book
                {
                    BookId = book.BookId,
                    BookName = book.BookName,
                    Pages = book.Pages,
                    Genre = book.Genre,
                    Publisher = book.Publisher,
                    Authors = new List<Author>(book.Authors)
                };

                entities.Add(entity);
                db.Books.Attach(entity);
                db.Books.Remove(entity);
            }
            db.SaveChanges();
        }

        return Json(entities.ToDataSourceResult(request, ModelState, book => new ViewModel
        {
            BookName = book.BookName,
            Pages = book.Pages,
            Genre = book.Genre,
            Publisher = book.Publisher,
            Authors = new List<Author>(book.Authors)
        }));
    }

    protected override void Dispose(bool disposing)
    {
        db.Dispose();
        base.Dispose(disposing);
    }
}

型号:

using System.Data.Entity;

public class Library : DbContext
{

    public Library()
       : base("name=Library")
    {
    }
    public DbSet<Book> Books { get; set; }
    public DbSet<Author> Authors { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

    }
}

}

public class Book
{
    public Book()
    {

    }
    [ScaffoldColumn(false)]
    public int BookId { get; set; }

    [Display(Name = "Book Name")]
    [MaxLength(100, ErrorMessage = "Book Name must be 100 characters or less"), MinLength(5)]
    public string BookName { get; set; }
    public int Pages { get; set; }

    public string Publisher { get; set; }

    public Genre Genre { get; set; }
    [JsonIgnore]
    public virtual ICollection<Author> Authors { get; set; }
}
public class Author
{
    public Author()
    {

    }
    [Required]
    public int AuthorId { get; set; }

    [Display(Name = "Author Name")]
    [MaxLength(100, ErrorMessage = "Author Name must be 100 characters or less"), MinLength(5)]
    public string AuthorName { get; set; }

    [JsonIgnore]
    public virtual ICollection<Book> Books { get; set; }
}

MyViewModel

public class ViewModel
{
    public ViewModel()
    {
        Authors = new List<Author>();
    }
    public int BookId { get; set; }

    public string BookName { get; set; }

    public int Pages { get; set; }

    public Genre Genre { get; set; }

    public string Publisher { get; set; }

    [UIHint("AuthorsEditor")]
    public List<Author> Authors { get; set; }
}

0 个答案:

没有答案