This is a migrated thread and some comments may be shown as answers.

Unexpected grid editor template

5 Answers 288 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Jochen
Top achievements
Rank 1
Jochen asked on 21 Jul 2020, 02:42 PM

I'm migrating some code from netFramework asp.net to asp.net core and I found some unexpected behavior with an editor used everywhere in my old code.

I'm bounding a timestamp property in a table like this:

columns.Bound(m => m.TimeSpan);

 

And I have an editor template for timestamps:

@model TimeSpan
 
@Html.Kendo().IntegerTextBoxFor(model=>model.Hours).Spinners(false).HtmlAttributes(new {style = "width: 30px" }).Placeholder("HH").Format("00") :
@Html.Kendo().IntegerTextBoxFor(model => model.Minutes).Min(0).Max(59).HtmlAttributes(new {style = "width: 30px;" }).Placeholder("MM").Spinners(false).Format("00")

 

If I load the page containing the table y get an exception:

System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ExpressionMetadataProvider.<>c__DisplayClass0_0`2.<FromLambdaExpression>g__modelAccessor|0(Object container)
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ModelExplorer.get_Model()
   at Kendo.Mvc.UI.Fluent.WidgetFactory`1.NumericTextBoxFor[TValue](Expression`1 expression)
   at Kendo.Mvc.UI.Fluent.WidgetFactory`1.IntegerTextBoxFor(Expression`1 expression)
.....

 

The EditorTemplate works normally if I use in other pages like:

@Html.EditorFor(m=>m.TimeSpan)

 

 

Thanks

5 Answers, 1 is accepted

Sort by
0
Jochen
Top achievements
Rank 1
answered on 21 Jul 2020, 02:51 PM

I don't know how to attach the full project but here is the controller:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Demo.Models;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using Microsoft.AspNetCore.Mvc.ModelBinding;
 
namespace Demo.Controllers
{
     
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
         
        private  static List<SampleObject> repo=new List<SampleObject>();
 
 
        public HomeController(ILogger<HomeController> logger)
        {
            if (repo.Count == 0)
            {
                for (int i = 1; i <= 3; i++)
                {
                    repo.Add(new SampleObject()
                    {
                        TimeSpan = DateTime.Now.TimeOfDay,
                        Id = i,
                    });
                }
            }
            _logger = logger;
        }
 
        public IActionResult Index()
        {
            return View();
        }
         
        public IActionResult NormalEditor()
        {
            return View(new SampleObject(){Id=1,TimeSpan = DateTime.Now.TimeOfDay});
        }
         
 
        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel {RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier});
        }
   //Table data source
        public virtual ActionResult Read([DataSourceRequest]DataSourceRequest request)
        {
            var jsonResult = Json(repo.ToDataSourceResult(request));
            return jsonResult;
        }
        [HttpPost]
        public virtual ActionResult Create([DataSourceRequest] DataSourceRequest request, SampleObject model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    model.Id=new Random(DateTime.Now.TimeOfDay.Milliseconds).Next();
                    repo.Add(model);
                    return Json(new[] { model }.ToDataSourceResult(request, ModelState));
                }
 
                return Json(new[] {model}.ToDataSourceResult(request, ModelState));
 
            }
            catch (Exception ex)
            {
                return Json(new[] {model}.ToDataSourceResult(request, ModelState));
            }
        }
        [HttpPost]
        public virtual ActionResult Update([DataSourceRequest]DataSourceRequest request, SampleObject model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    repo.Remove(repo.First(i => i.Id == model.Id));
                    repo.Add(model);
                }
 
                return Json(new[] { model }.ToDataSourceResult(request, ModelState));
            }
            catch(Exception ex)
            {
                return Json(new[] { model }.ToDataSourceResult(request, ModelState));
            }
        }
        [HttpPost]
        public virtual ActionResult Destroy([DataSourceRequest]DataSourceRequest request, SampleObject model)
        {
            try
            {
                repo.Remove(repo.First(i => i.Id == model.Id));
                return Json(new[] {model}.ToDataSourceResult(request, ModelState));
            }
            catch (Exception ex)
            {
                return Json(new[] {model}.ToDataSourceResult(request, ModelState));
            }
        }
        //Table data source
         
      
    }
 
    public class SampleObject
    {
        public int Id { get; set; }
        public TimeSpan TimeSpan { get; set; }
    }
}

 

The editor working in Views/home/NormalEditor.html

@using Demo.Controllers
@model SampleObject
@{
    ViewData["Title"] = "Home Page";
}
@Html.EditorFor(m=>m.Id)
@Html.EditorFor(m=>m.TimeSpan)

Views/Home/index.html

@using Microsoft.VisualBasic
@using Demo.Controllers
@{
    ViewData["Title"] = "Home Page";
}
 
 
@(Html.Kendo().Grid<SampleObject>()
    .Name("grid")
    .Scrollable(s=>s.Height("calc( 100vh - 310px )"))
    .Columns(columns =>
    {
        columns.Bound(m => m.Id);
        columns.Bound(m => m.TimeSpan);
        columns.Command(command => { command.Edit().Text(" ").UpdateText("Update"); command.Destroy().Text(" "); }).Width(155);
    })
    .ToolBar(toolbar =>
    {
        toolbar.Create();
    })
    .Editable(editable => editable.Mode(GridEditMode.InLine))
    .Filterable()
    .Pageable()
    .Sortable()
    .DataSource(dataSource => dataSource
        .Ajax()
        .ServerOperation(false)
        .Model(model =>
        {
            model.Id(m => m.Id);
        })
        .Read(read => read.Action("Read", "Home" ))
        .Create(create => create.Action("Create", "Home" ))
        .Update(update => update.Action("Update", "Home" ))
        .Destroy(destroy => destroy.Action("Destroy", "Home" ))
    )
    )
0
Petar
Telerik team
answered on 24 Jul 2020, 01:13 PM

Hi Jochen,

Thank you for the provided code. Based on it, I cannot say what is the reason for issue. To be able to help you, I will need a runnable project in which the reported behavior can be replicated. You can archive your current project or isolate a new one in which the discussed issue can be reproduced. By archiving your project, you can send it to us as a Zip file. 

Being able to reproduce the issue, we can further investigate what is the reason for it and provide a relevant fix. If you don't want to publicly share your code, you can submit another support ticket and share your project in it. 

Regards,
Petar
Progress Telerik

0
Jochen
Top achievements
Rank 1
answered on 24 Jul 2020, 03:35 PM

Working project reproducing the error:

https://drive.google.com/file/d/1AFaUq2KrC4yXKVRfvSWvEYnQ7XOwYXgB/view?usp=sharing

0
Petar
Telerik team
answered on 29 Jul 2020, 03:26 PM

Hi Jochen,

We are still working on the current case and we will need more time to answer you.

We will write to you back with more details about the discussed scenario once we have more information to share. 

Regards,


Petar
Progress Telerik

0
Petar
Telerik team
answered on 29 Jul 2020, 04:59 PM

Hi Jochen,

Attached to my reply you will find the version of the provided project that correctly loads the custom editor for the TimeSpan field of the Grid. 

There are two template options defined in the attached project - one that uses Helpers and one without helpers. 

The one without helper can be defined like this:

@model Demo.Models.SampleObject

<input name="TimeSpan.Hours" data-bind="value:TimeSpan.Hours" data-format="n0" data-role="numerictextbox" data-spinners="false" style="width: 50px;" />:
<input name="TimeSpan.Minutes" data-bind="value:TimeSpan.Minutes" data-format="n0" data-role="numerictextbox" data-spinners="false" style="width: 50px;" />

The template with helper can be defined as follows:

@model Demo.Models.SampleObject

@Html.Kendo().IntegerTextBoxFor(model => model.TimeSpan.Hours).HtmlAttributes(new { style = "width: 50px;", data_bind = "value:TimeSpan.Hours" }).Spinners(false) :
@Html.Kendo().IntegerTextBoxFor(model => model.TimeSpan.Minutes).HtmlAttributes(new { style = "width: 50px;", data_bind = "value:TimeSpan.Minutes" }).Spinners(false)

Check the attached example and let me know if you have any questions related to the provided implementation. 

Regards,
Petar
Progress Telerik

Tags
Grid
Asked by
Jochen
Top achievements
Rank 1
Answers by
Jochen
Top achievements
Rank 1
Petar
Telerik team
Share this question
or