[OPEN] [#837] Object reference not set to an instance of an object when using GridPanel with Data annotation

Page 1 of 2 12 LastLast
  1. #1

    [OPEN] [#837] Object reference not set to an instance of an object when using GridPanel with Data annotation

    This issue was previously reported here: http://forums.ext.net/showthread.php...on-not-working

    The error is a NullReferenceException when using the GridPanel with data annotation:

    System.NullReferenceException was unhandled by user code
      HResult=-2147467261
      Message=Object reference not set to an instance of an object.
      Source=App_Web_hllijq3o
      StackTrace:
           at ASP._Page_Views_OpenPayments_Index_cshtml.Execute() in g:\VisualStudio\Visual Studio 2013\Websites\BugExtNetDateFormat\BugExtNetDateFormat\Views\OpenPayments\Index.cshtml:line 171
           at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
           at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
           at System.Web.WebPages.StartPage.RunPage()
           at System.Web.WebPages.StartPage.ExecutePageHierarchy()
           at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
           at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
           at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
           at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
           at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
           at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)
           at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)
      InnerException:
    The error occurs when [DateColumn(Format = "d")] is used in the model to annotate an SQL column.

    View:
    @using Ext.Net;
    @using Ext.Net.MVC;
    @model IEnumerable<BugExtNetDateFormat.OpenPayment>
    
    @{
        ViewBag.Title = "Index";
        var X = Html.X();    
    }
    
    <h2>List</h2>
    <p>
        @(Html.X().ResourceManager())
        @(X.GridPanel()
                   .ID("GridPanel1")
                        .Store(X.StoreForModel().ID("Store1")
                        .Sorters(X.DataSorter().Property("Licence_id").Direction(Ext.Net.SortDirection.ASC)))
                    .Icon(Icon.Table)
                    .Title("Licences")
                    .Width(900)
                    .Height(350)
                    .ColumnModel(
                        X.CommandColumn()
                           .Width(70)
                           .Commands(
                                Html.X().GridCommand()
                                    .Text("Reject")
                                    .ToolTip(t =>
                                    {
                                        t.Text = "Reject row changes";
                                    })
                                    .CommandName("reject")
                                    .Icon(Icon.ArrowUndo)
                           )
                .PrepareToolbar(t =>
                                   {
                                       t.Handler = "toolbar.items.get(0).setVisible(record.dirty);";
                                   })
               .Listeners(l =>
               {
                   l.Command.Handler = "record.reject();";
               }),
                        X.ColumnFor(Model, m => m.Date)
                            .ToBuilder<Column.Builder>()
                            .Flex(1)
                            .Editor(X.DateField().AllowBlank(false)),
                            X.ColumnFor(Model, m => m.Customer).ToBuilder<Column.Builder>()
                                .Flex(1)
                                .Editor(X.TextField().AllowBlank(true)),
                            X.ColumnFor(Model, m => m.Currency).ToBuilder<Column.Builder>()
                                .Flex(1)
                                .Editor(X.TextField().AllowBlank(true)),
                        X.ColumnFor(Model, m => m.Amount)
                            .ToBuilder<Column.Builder>()
                            .Flex(1)
                            .Editor(X.NumberField().AllowBlank(true))
                   )
    .SelectionModel(X.CheckboxSelectionModel().Mode(SelectionMode.Multi))
    .Plugins(X.FilterHeader())
    .BottomBar(X.PagingToolbar().HideRefresh(true))
    .DockedItems(
    X.Toolbar()
    .Dock(Dock.Bottom)
    .Items(
    X.Button()
    .Text("Case Sensitive")
    .EnableToggle(true)
    .AllowDepress(true)
    .ToggleHandler("var plugin = this.up('GridPanel1').filterHeader; plugin.caseSensitive = this.pressed; plugin.applyFilter();"),
    X.Button()
    .Text("Load Filters")
    .Handler("loadFilter(this.up('GridPanel1').filterHeader);"),
    X.Button()
    .Text("Get Fields Values")
    .ToolTip("Get Values of Fields")
    .Handler("var values = Ext.encode(this.up('GridPanel1').filterHeader.getValue()); Ext.Msg.alert('Fields Values', values);"),
    X.Button()
    .Text("Get Filter Values")
    .ToolTip("Get Filter Values of Grid")
        .Handler("var filters = Ext.encode(this.up('GridPanel1').filterHeader.getFilterValues()); Ext.Msg.alert('Filter Values', filters);"),
    X.Button()
    .Text("Clear Filters")
    .Handler("this.up('grid').filterHeader.clearFilter();"),
    X.Button()
            .Text("Sync")
            .Icon(Icon.Disk)
            .DirectEvents(de =>
            {
                de.Click.Url = Url.Action("HandleChanges");
                de.Click.ExtraParams.Add(new Parameter
                {
                    Name = "data",
                    Value = "this.up('GridPanel1').store.getChangedData()",
                    Mode = ParameterMode.Raw,
                    Encode = true
                });
            })
    
    
    )
    )
        .Plugins(
            Html.X().CellEditing()
        )
    .Listeners(l =>
    {
        l.AfterRender.Handler = "this.filterHeader.fields[0].setIconCls('#Magnifier')";
        l.AfterRender.Delay = 10;
    }))
        }
        }
    
    
    </p>
    Model:

    namespace BugExtNetDateFormat
    {
        using System;
        using System.Collections.Generic;
        
        public partial class OpenPayment
        {
            [ModelField(IDProperty = true, UseNull = true)]
            [Field(Ignore = true)]      
            public int id { get; set; }
            [ModelField(Ignore = true)]
            public string PhantomId
            {
                get;
                set;
            }
            public string Customer { get; set; }
            //[Column(Text = "Payment Due")]
            [DateColumn(Format = "d")]
            public Nullable<System.DateTime> Date { get; set; }
            public string Currency { get; set; }
            public Nullable<decimal> Amount { get; set; }
            public string Via { get; set; }
            public string Notes { get; set; }
            public Nullable<bool> Received { get; set; }
        }
    }
    We have provided a sample VS2013 project on Google drive. Please see separate email.
    Last edited by Daniil; Jul 17, 2015 at 4:35 PM. Reason: [OPEN] [#837]
  2. #2
    Hi @PocketPrograms,

    Welcome to the Ext.NET forums and thank you for the report!

    We've reproduced and will investigate.

    Created an Issue:
    https://github.com/extnet/Ext.NET/issues/837
  3. #3
    Please replace
    X.ColumnFor(Model, m => m.Date)
        .ToBuilder<Column.Builder>()
    to
    X.ColumnFor(Model, m => m.Date)
        .ToBuilder<DateColumn.Builder>()
  4. #4
    That resolves the error, however the date format used is the format of the server (mm/dd/yyyy) and not of the client PC (dd/mm/yyyy). Is there a way to use the international settings of the client PC for this?
  5. #5
    Yes, [DateColumn(Format = "d")] setting means the server side format.

    To use a client side, I can suggest to try the following.

    1. Remove (Format = "d")
    2. Set .Locale("client") for ResourceManager

    .Locale("client") means that a Locale will be taken from HttpContext.Current.Request.UserLanguages. So, if a browser's locale is supported in Ext.NET, then a DateColumn should appear with a proper date format.
  6. #6
    Thanks Daniil,

    We are using the GridPanel in an MVC project. One column includes a date.

    What we are trying to achieve is that the date is displayed in short date format (e.g. 03/08/2015) in the locale of the client PC. The editor should use the same format.

    What is the best way to achieve this?
    Last edited by PocketPrograms; Aug 04, 2015 at 10:31 PM.
  7. #7
    Please clarify have you tried with .Locale("client")? It is the first thing that I would Does it not work for you?

    This example appears to be working for me.

    Example
    @{
        var X = Html.X();
    }
    
    <!DOCTYPE html>
    <html>
    <head>
        <title>Ext.Net.MVC v3 Example</title>
    </head>
    <body>
        @X.ResourceManager().Locale("client")
    
        @(X.GridPanel()
            .Store(X.Store()
                .Model(X.Model()
                    .Fields("date", ModelFieldType.Date)
                )
                .DataSource(new object[]
                {
                    new
                    {
                        date = DateTime.Today    
                    },
                    new
                    {
                        date = DateTime.Today.AddDays(1)
                    }
                })
            )
            .ColumnModel(
                X.DateColumn()
                    .Text("Date")
                    .DataIndex("date")
                    .Editor(X.DateField())
            )
            .Plugins(X.CellEditing())
        )
    </body>
    </html>
  8. #8
    Daniil,

    the date is using the correct client locale, but the format is not the short date format. The date is displayed as Sun Aug 17 2014 00:00:00 GMT+10 (AUS Eastern Standard Time).

    We want the date to be displayed as a short date using the clients locale, e.g. 17/08/2014

    What do we need to add to get the column to display the data in the column as a short date using the client locale?
  9. #9
    I could not reproduce it.

    Please provide a full, but simplified, test case to reproduce it.
  10. #10
    Hi Daniil,

    We have built a new sample. This is the result:

    Click image for larger version. 

Name:	2015-08-11 09_01_40-192.168.22.101 - Remote Desktop Connection.png 
Views:	45 
Size:	6.8 KB 
ID:	24139

    Model:
    using System;
    using System.Collections.Generic;
    using System.Web;
    using Ext.Net.MVC;
    
    namespace CustomerPortal
    {
        [Model(Name = "Test")]
        public partial class ExtTestModel
        {
            [ModelField(IDProperty = true, UseNull = true)]
            [Field(Ignore = true)]
            public int? id { get; set; }
            [PresenceValidator]
            //[DateColumn(Format = "d")]
            public Nullable<System.DateTime> Date { get; set; }
        }
    }
    Controller:
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Entity;
    using System.Linq;
    using System.Net;
    using System.Web;
    using System.Web.Mvc;
    using Ext.Net.MVC;
    
    namespace CustomerPortal
    {
        [RequireHttps]
        public class ExtTestController : Controller
        {
             // GET: OpenPayments
            public ActionResult Index()
            {
                return View();
            }
            // GET: OpenPayments/Details/5
            [AcceptVerbs(HttpVerbs.Get)]
            public RestResult Read(ExtTestModel test)
            {
                List<ExtTestModel> list = new List<ExtTestModel>();
                ExtTestModel testData = new ExtTestModel();
                testData.id = 1;
                testData.Date = DateTime.Now;
                list.Add(testData);
                try
                {
                    return new RestResult
                    {
                        Success = true,
                        Data = list
                    };
                }
                catch (Exception e)
                {
                    return new RestResult
                    {
                        Success = false,
                        Message = e.Message
                    };
                }
            }
    
        }
    }
    View:
    @model IEnumerable<ExtTestModel>
    @{
        ViewBag.Title = "Date Demo";
    }
    @Html.X().ResourceManager().Locale("client")
    <script>
        //var getTokenValue = function () {
        //    return $('[name=__RequestVerificationToken]').val();
        //};
        //var token = $('[name=__RequestVerificationToken]').val();
        var onWrite = function (store, operation) {
            var record = operation.getRecords()[0],
                name = Ext.String.capitalize(operation.action),
                verb;
    
            if (name == 'Destroy') {
                verb = 'Destroyed';
            } else {
                verb = name + 'd';
            }
    
            Ext.net.Notification.show({ title: name, html: Ext.String.format("{0} customer: {1}<br/>{2}", verb, record.getId(), operation.getResultSet().message) });
        }
    </script>
    
    
    <h1>Date Demo</h1>
    
    @(Html.X().GridPanel()
                .Icon(Icon.Table)
                .Frame(true)
                .Title("Open Payments")
                .Height(400)
                .Width(1000)
                .Store(
                    Html.X().StoreForModel().Control(s =>
                    {
                        s.AutoSync = true;
                        s.Proxy.Add(
                            new RestProxy
                            {
                                AppendAction = false,
                                Reader = {
                                    new JsonReader {
                                        RootProperty = "data",
                                        MessageProperty = "message"
                                    }
                                },
                                API =
                                {
                                    Read = Url.Action("Read"),
                                    Update = Url.Action("Update"),
                                    Create = Url.Action("Create"),
                                    Destroy = Url.Action("Destroy")
                                },
                                Writer = {
                                    new JsonWriter
                                    {
                                        AllowSingle = true
                                    }
                                }
                            }
                        );
                        s.Listeners.Write.Fn = "onWrite";
                        s.Listeners.Write.Delay = 1;
                    })
                )
                .ColumnModel(
                    Html.X().ColumnFor(Model, m => m.id)
                        .ToBuilder<Column.Builder>()
                        .Width(40)
                        .Renderer("return record.phantom ? '' : value;"),
                        @*Html.X().ColumnFor(Model, m => m.Date)
        .ToBuilder<DateColumn.Builder>()
        .Flex(1)
        .Editor(
            Html.X().DateField().AllowBlank(false)
        )*@
     Html.X().ColumnFor(Model, m => m.Date)
                .ToBuilder<Column.Builder>()
                .Flex(1)
                .Align(Alignment.Right)
    .Editor(
                        Html.X().DateField().AllowBlank(false)
                    )
                                    )
                                    .TopBar(
                                        Html.X().Toolbar()
                                            .Items(
                                                Html.X().Button()
                                                    .Text("Add")
                                                    .Icon(Icon.Add)
                                                    .Handler("this.up('grid').store.insert(0, new Test());this.up('grid').editingPlugin.startEdit(0, 0);"),
                                                Html.X().Button()
                                                    .ItemID("btnRemove")
                                                    .Text("Delete")
                                                    .Icon(Icon.Exclamation)
                                                    .Handler("this.up('grid').deleteSelected();")
                                            )
                                    )
                                    .Plugins(
                                        Html.X().RowEditing()
                                            .Listeners(l =>
                                            {
                                                l.CancelEdit.Handler = "if(e.record.phantom){e.store.remove(e.record);}";
                                            })
                                    )
    )
    Note: Changing the builder for the date column to DateColumn.Builder (shown in commented out code in the view) to causes System.NullReferenceException exception.
Page 1 of 2 12 LastLast

Similar Threads

  1. Replies: 2
    Last Post: Apr 07, 2014, 11:00 PM
  2. Replies: 2
    Last Post: Jun 13, 2013, 3:58 PM
  3. Replies: 2
    Last Post: Dec 17, 2012, 3:00 AM
  4. Replies: 1
    Last Post: Jun 27, 2012, 9:19 PM
  5. Replies: 0
    Last Post: Jun 03, 2009, 4:18 AM

Posting Permissions