powered by simpleCommunicator - 2.0.59     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / ASP.NET [игнор отключен] [закрыт для гостей] / ASP.NET with KENDO UI
4 сообщений из 29, страница 2 из 2
ASP.NET with KENDO UI
    #38739642
Фотография hVostt
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Alonmaster,

Вот пример из поставки

Вью модели:

Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
    public class CategoryViewModel
    {
        public int CategoryID { get; set; }
        public string CategoryName { get; set; }
    }

    public class ProductViewModel
    {
        [ScaffoldColumn(false)]
        public int ProductID
        {
            get;
            set;
        }

        [Required]
        [DisplayName("Product name")]
        public string ProductName
        {
            get;
            set;
        }

        [DisplayName("Unit price")]
        [DataType(DataType.Currency)]
        [Range(0, int.MaxValue)]
        public decimal UnitPrice
        {
            get;
            set;
        }

        [DisplayName("Units in stock")]
        [DataType("Integer")]
        [Range(0, int.MaxValue)]
        public int UnitsInStock
        {
            get;
            set;
        }

        public bool Discontinued
        {
            get;
            set;
        }

        [DisplayName("Last supply")]
        [DataType(DataType.Date)]
        public DateTime LastSupply
        {
            get;
            set;
        }

        [DataType("Integer")]
        public int UnitsOnOrder 
        { 
            get; 
            set; 
        }

        [UIHint("ClientCategory")]
        public CategoryViewModel Category 
        { 
            get; 
            set; 
        }

        public int? CategoryID { get; set; }

        public string QuantityPerUnit { get; set; }
    }



Шаблон ClientCategory.cshtml

Код: html
1.
2.
3.
4.
5.
6.
7.
@model Kendo.Mvc.Examples.Models.CategoryViewModel

@(Html.Kendo().DropDownListFor(m => m)
        .DataValueField("CategoryID")
        .DataTextField("CategoryName")
        .BindTo((System.Collections.IEnumerable)ViewData["categories"])
)



Контроллер:

Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
    public class GridController : Controller
    {
        public ActionResult Index()
        {            
            PopulateCategories();
            return View();
        }

        public ActionResult Read([DataSourceRequest] DataSourceRequest request)
        {
            return Json(productService.Read().ToDataSourceResult(request));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Update([DataSourceRequest] DataSourceRequest request, 
            [Bind(Prefix = "models")]IEnumerable<ProductViewModel> products)
        {
            if (products != null && ModelState.IsValid)
            {
                foreach (var product in products)
                {
                    productService.Update(product);
                }
            }

            return Json(products.ToDataSourceResult(request,ModelState));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create([DataSourceRequest] DataSourceRequest request, 
            [Bind(Prefix = "models")]IEnumerable<ProductViewModel> products)
        {
            var results = new List<ProductViewModel>();

            if (products != null && ModelState.IsValid)
            {
                foreach (var product in products)
                {
                    productService.Create(product);

                    results.Add(product);
                }
            }

            return Json(results.ToDataSourceResult(request, ModelState));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Destroy([DataSourceRequest] DataSourceRequest request,
            [Bind(Prefix = "models")]IEnumerable<ProductViewModel> products)
        {
            foreach (var product in products)
            {
                productService.Destroy(product);
            }

            return Json(products.ToDataSourceResult(request, ModelState));
        }
  

        private void PopulateCategories()
        {
            var dataContext = new SampleEntities();
            var categories = dataContext.Categories
                        .Select(c => new CategoryViewModel {
                            CategoryID = c.CategoryID,
                            CategoryName = c.CategoryName
                        })
                        .OrderBy(e => e.CategoryName);

            ViewData["categories"] = categories;
            ViewData["defaultCategory"] = categories.First();            
        }

        private void PopulateEmployees()
        {
            ViewData["employees"] = new SampleEntities().Employees
                        .Select(e => new EmployeeViewModel
                        {
                            EmployeeID = e.EmployeeID,
                            EmployeeName = e.FirstName + " " + e.LastName
                        })
                        .OrderBy(e => e.EmployeeName);
        }
    }



и вью Index.cshtml

Код: html
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
@(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.ProductViewModel>()
    .Name("grid")
    .Columns(columns =>
    {
        columns.Bound(p => p.ProductName);
        columns.Bound(p => p.Category).ClientTemplate("#=Category.CategoryName#").Width(160);
        columns.Bound(p => p.UnitPrice).Width(120);
        columns.Command(command => command.Destroy()).Width(90);
    })
    .ToolBar(toolBar =>
        {
            toolBar.Create();
            toolBar.Save();
        })
    .Editable(editable => editable.Mode(GridEditMode.InCell))
    .Pageable()
    .Sortable()
    .Scrollable()
    .HtmlAttributes(new { style = "height:430px;" })
    .DataSource(dataSource => dataSource
        .Ajax()
        .Batch(true)
        .ServerOperation(false)
        .Events(events => events.Error("error_handler"))
        .Model(model =>
        {
            model.Id(p => p.ProductID);
            model.Field(p => p.ProductID).Editable(false);
            model.Field(p => p.Category).DefaultValue(
                ViewData["defaultCategory"] as Kendo.Mvc.Examples.Models.CategoryViewModel);
        })
        .PageSize(20)
        .Read(read => read.Action("Read", "Grid"))
        .Create(create => create.Action("Create", "Grid"))
        .Update(update => update.Action("Update", "Grid"))        
        .Destroy(destroy => destroy.Action("Destroy", "Grid"))
    )
)

<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);
        }
    }
</script>



Один в один ваша задача.

Результат: http://demos.telerik.com/aspnet-mvc/grid/editing-custom

Категории в выпадающем списке.
...
Рейтинг: 0 / 0
ASP.NET with KENDO UI
    #38741182
Alonmaster
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Спасибо) Я сделал по примеру, но возникает ошибка, которую я обойти не могу. После удаления данных,и при нажатии на "Сохранить изменения", появляется ошибка "Исключение типа "System.Data.Entity.Infrastructure.DbUpdateException" возникло в EntityFramework.dll, но не было обработано в коде пользователя"

Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
 [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditingCustom_Destroy([DataSourceRequest] DataSourceRequest request,[Bind(Prefix = "models")] IEnumerable<StreetViewModel> streets)
        {
            if (streets.Any())
            {
                foreach (var street in streets)
                {
                    streetService.Destroy(street);
                }
            }
            return Json(streets.ToDataSourceResult(request, ModelState));
        }



Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
public void Destroy(StreetViewModel street)
        {
            var entity = new Street();

            entity.StreetID = street.StreetID;

            db.Streets.Attach(entity);

            db.Streets.Remove(entity);

            db.SaveChanges();

        }



Модель:

Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
 public class StreetViewModel 
    {
        [ScaffoldColumn(false)]
        public int StreetID { get; set; }
        public string StreetName { get; set; }

        [UIHint("ClientCity")]
        public CityViewModel City{ get; set; }
        public int? CityID { get; set; }

        [UIHint("ClientRajon")]
        public RajonViewModel Rajon { get; set; }
        public int? RajonID { get; set; }

        [UIHint("ClientStreetTypeList")]
        public StreetTypeListModel StreetTypeList { get; set; }
        public int? StreetTypeID { get; set; }
       
    }
...
Рейтинг: 0 / 0
ASP.NET with KENDO UI
    #38741334
Фотография hVostt
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
AlonmasterСпасибо) Я сделал по примеру, но возникает ошибка, которую я обойти не могу. После удаления данных,и при нажатии на "Сохранить изменения", появляется ошибка "Исключение типа "System.Data.Entity.Infrastructure.DbUpdateException" возникло в EntityFramework.dll, но не было обработано в коде пользователя"

Это уже проблема на уровне базы данных. Возможно нарушаются констрейты, отлови ошибку в try { } catch { } и запиши текст ошибки в лог. Или пройдись дебаггером, посмотри почему возникает ошибка.
...
Рейтинг: 0 / 0
ASP.NET with KENDO UI
    #38743399
Alonmaster
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Проблема решилась полной очисткой всех таблиц!
Подскажите, как правильно сделать, чтобы выпадающий список состоял из двух слов, которые из разных подчиненных таблиц.
...
Рейтинг: 0 / 0
4 сообщений из 29, страница 2 из 2
Форумы / ASP.NET [игнор отключен] [закрыт для гостей] / ASP.NET with KENDO UI
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]