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

Form error on Model State Errors

11 Answers 2731 Views
Form
This is a migrated thread and some comments may be shown as answers.
Dave
Top achievements
Rank 1
Dave asked on 28 May 2020, 03:03 PM

When using a new form to post if adding model state errors with a key value other than string.empty the kendo().form throws error on return to view:

Message "Object reference not set to an instance of an object."string

Source: "Kendo.Mvc"string

Stack trace:

"   at Kendo.Mvc.UI.Form`1.BuildItems(IList`1 items)\r\n   at Kendo.Mvc.UI.Form`1.WriteInitializationScript(TextWriter writer)\r\n   at Kendo.Mvc.UI.WidgetBase.WriteHtml(HtmlTextWriter writer)\r\n   at Kendo.Mvc.UI.Form`1.WriteHtml(HtmlTextWriter writer)\r\n   at Kendo.Mvc.UI.WidgetBase.ToHtmlString()\r\n   at Kendo.Mvc.UI.Fluent.WidgetBuilderBase`2.ToHtmlString()\r\n   at System.Web.HttpUtility.HtmlEncode(Object value)\r\n   at System.Web.WebPages.WebPageBase.Write(Object value)\r\n   at ASP._Page_Views_User_CreateUser_cshtml.Execute() in C:\\CustomerVS2019Projects\\iCepts\\CustomerPortal\\Views\\User\\CreateUser.cshtml:line 17\r\n   at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()\r\n   at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()\r\n   at System.Web.WebPages.StartPage.RunPage()\r\n   at System.Web.WebPages.StartPage.ExecutePageHierarchy()\r\n   at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)\r\n   at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)\r\n   at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)\r\n   at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)\r\n   at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)\r\n   at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)\r\n   at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)"

11 Answers, 1 is accepted

Sort by
0
Dimitar
Telerik team
answered on 29 May 2020, 06:38 AM

Hello Dave,

I am attaching a simple ASP.NET MVC solution where you can find a Form configured with two fields - "FirstName" and "LastName". Both fields have required model validation, and also a server error when FirstName is equal to LastName. To test it, simply type "test" in both fields and hit the submit button. As a result, the ModelState error that is set in the controller end-point will be successfully displayed.

May I ask you to review the example and confirm if it works correctly on your end? Also, could you share what modifications have to be done to the current setup so that the described error message is shown?

Regards,
Dimitar
Progress Telerik

Progress is here for your business, like always. Read more about the measures we are taking to ensure business continuity and help fight the COVID-19 pandemic.
Our thoughts here at Progress are with those affected by the outbreak.
0
Dave
Top achievements
Rank 1
answered on 29 May 2020, 03:21 PM

Hi,

Thanks for your code! It works but does not lead me to my issue.

 

The error is in the CreateUser. The UpdateUser code is not finished.

Here is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Management;
using System.Web.Mvc;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using Microsoft.NAV;
using Microsoft.Graph;
using b2c_ms_graph;
using System.Threading.Tasks;
using CustomerPortal.Properties;

namespace CustomerPortal.Controllers
{
    [Authorize]
    public class UserController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult CreateUser()
        {

            return View(newUser());
        }

        public UserModel newUser()
        {
            var newUser = new b2c_ms_graph.UserModel();
            newUser.extension_39d2bd21d67b480891ffa985c6eb1398_TenantId = ODataWebService.TenantId();
            newUser.extension_39d2bd21d67b480891ffa985c6eb1398_CompanyId = ODataWebService.CompanyId();
            newUser.extension_39d2bd21d67b480891ffa985c6eb1398_WebRole = int.Parse(ODataWebService.WebRole()) + 1;
            newUser.forcePasswordChange = false;
            newUser.DisplayAccountEnabled = true;

            return newUser;
        }


        [HttpPost()]
        public async Task<ActionResult> CreateUser(b2c_ms_graph.UserModel userModel, FormCollection formCollection)
        {
            if (string.IsNullOrEmpty(userModel.newPassword))
                ModelState.AddModelError("newPassword", "New Password is required.");

            if (userModel.newPassword != userModel.confirmPassword)
                ModelState.AddModelError(string.Empty, "New Password and confirm password do not match.");

            if (ModelState.IsValid)
            {
                try
                {
                    User newUser = new User();
                    IDictionary<string, object> extensionInstance = new Dictionary<string, object>();
                    extensionInstance.Add(B2cCustomAttributeHelper.GetCompleteAttributeName("WebRole"), int.Parse(ODataWebService.WebRole()) + 1);
                    extensionInstance.Add(B2cCustomAttributeHelper.GetCompleteAttributeName("TenantId"), ODataWebService.TenantId());
                    extensionInstance.Add(B2cCustomAttributeHelper.GetCompleteAttributeName("CompanyId"), userModel.extension_39d2bd21d67b480891ffa985c6eb1398_CompanyId);
                    extensionInstance.Add(B2cCustomAttributeHelper.GetCompleteAttributeName("CustomerNumber"), userModel.extension_39d2bd21d67b480891ffa985c6eb1398_CustomerNumber);
                    newUser.AdditionalData = extensionInstance;

                    newUser.DisplayName = userModel.DisplayName;
                    newUser.AccountEnabled = userModel.DisplayAccountEnabled;
                    newUser.PasswordProfile = new PasswordProfile
                    {
                        Password = userModel.newPassword,
                        ForceChangePasswordNextSignIn = userModel.forcePasswordChange
                    };

                    newUser.PasswordPolicies = "DisablePasswordExpiration";
                    newUser.Identities = new List<ObjectIdentity>
               {
                 new ObjectIdentity
                 {
                   SignInType = "emailAddress",
                   Issuer = "ICPCustomerPortal1.onmicrosoft.com",
                   IssuerAssignedId = userModel.DisplayEmailName
                 }
               };

                    GraphServiceClient graphClient = GraphClient.CreateGraphClient();

                    await graphClient.Users
                                     .Request()
                                     .AddAsync(newUser);

                    return RedirectToAction("Index");

                }

                catch (Exception ex)
                {
                    ModelState.AddModelError(string.Empty, ex.Message);
                };
            }

            return View(userModel);
        }



        public async Task<ActionResult> DeleteUser(DataSourceRequest request, string Id)
        {
            ModelStateDictionary iModelState = new ModelStateDictionary();

            if (ModelState.IsValid)
            {
                if (!string.IsNullOrEmpty(Id))
                {
                    try
                    {
                        GraphServiceClient graphClient = GraphClient.CreateGraphClient();

                        await graphClient.Users[Id]
                         .Request()
                         .DeleteAsync();

                        return View("Index");
                    }
                    catch (Exception ex)
                    {
                        iModelState.AddModelError(string.Empty, ex.Message);
                    }
                }
            }
            else
                iModelState = ModelState;

            return View(iModelState);
        }

 

       
        public async Task<ActionResult> UpdateUser(DataSourceRequest request, string Id)
        {
            if (!string.IsNullOrEmpty(Id))
            {
                try
                {
                    GraphServiceClient graphClient = GraphClient.CreateGraphClient();

                    var user = await graphClient.Users[Id]
                                                .Request()
                                                .GetAsync();

                    return View(user);
                }
                catch (Exception ex)
                {
                }
            }

            return RedirectToAction("Index");
        }

        [HttpPut()]
        public async Task<ActionResult> UpdateUser(b2c_ms_graph.UserModel userModel, FormCollection formCollection)
        {
            if (string.IsNullOrEmpty(userModel.newPassword))
                ModelState.AddModelError(string.Empty, "New Password is required.");

            if (userModel.newPassword != userModel.confirmPassword)
                ModelState.AddModelError(string.Empty, "New Password and confirm password do not match.");

            if (ModelState.IsValid)
            {
                try
                {
                    GraphServiceClient graphClient = GraphClient.CreateGraphClient();

                    await graphClient.Users[userModel.Id]
                                     .Request()
                                     .UpdateAsync(userModel);

                    return RedirectToAction("Index");
               }

                catch (Exception ex)
                {
                    ModelState.AddModelError(string.Empty, ex.Message);
                };
            }

            return View(userModel);
        }

    }
}

 

@model b2c_ms_graph.UserModel
@using System.Security.Claims;

@{
    ViewBag.Title = "Create User";

    var gcustomerNumber = ClaimsPrincipal.Current.Claims.Where(w => w.Type == "extension_CustomerNumber").Select(s => s.Value).FirstOrDefault();
    var gwebRole = ClaimsPrincipal.Current.Claims.Where(w => w.Type == "extension_WebRole").Select(s => s.Value).FirstOrDefault();
    Boolean filterCustomer = (gwebRole != "1");

}

 
   @(Html.Kendo().Form<b2c_ms_graph.UserModel>()
    .Name("CreateUser")
    .HtmlAttributes(new { action = "", method = "POST" })
    .Items(items =>
    {
        items.AddGroup()
        .Label("Create User")
        .Items(i =>
        {
            i.Add()
        .Field(f => f.extension_39d2bd21d67b480891ffa985c6eb1398_CompanyId)
        .Label(l => l.Text("Company:"))
            .Editor(e =>
            {
                e.ComboBox()
                .Name("extension_39d2bd21d67b480891ffa985c6eb1398_CompanyId")
                .DataTextField("displayName")
                .DataValueField("id")
                .HtmlAttributes(new { style = "width:100%" })
                .AutoBind(true)
                .Events(ev => ev.Change("changeCompany"))
                .DataSource(s => s.Read(r => r.Action("GetCompanies", "Company")).ServerFiltering(true));
            });
            i.Add()
        .Field(f => f.DisplayEmailName)
        .Label(l => l.Text("Email Address:"));
            i.Add()
        .Field(f => f.DisplayName)
        .Label(l => l.Text("Display Name:"));
            i.Add()
        .Field(f => f.extension_39d2bd21d67b480891ffa985c6eb1398_CustomerNumber)
        .Label(l => l.Text("Customer:"))
            .Editor(e =>
            {
                e.ComboBox()
            .Name("extension_39d2bd21d67b480891ffa985c6eb1398_CustomerNumber")
            .DataTextField("displayName")
            .DataValueField("number")
            .HtmlAttributes(new { style = "width:100%" })
            .AutoBind(true)
            .DataSource(s => s.Read(r => r.Action("GetCustomers", "Customer").Data("getCompanyId")).ServerFiltering(true));
            });
            i.Add()
        .Field(f => f.newPassword)
        .Label(l => l.Text("Password:"));
            i.Add()
        .Field(f => f.confirmPassword)
        .Label(l => l.Text("Confirm Password:"));
            i.Add()
        .Field(f => f.forcePasswordChange)
        .Label(l => l.Text("Force Password Change:"));
            //.Editor(e => e.Switch().Name("forcePasswordChange"));
            i.Add()
            .Field(f => f.DisplayAccountEnabled)
            .Label(l => l.Text("Enable Account:"));
            //.Editor(e => e.Switch().Name("DisplayAccountEnabled"));

        });
    })
    )


<script>
    $(document).ready(function () {
        $("#newPassword").attr("type", "password");
        $("#confirmPassword").attr("type", "password");
        
    });


    //function onFormValidateField(e) {
    //    debugger;
    //    $("#validation-success").html("");
    //}

    //function onFormSubmit(e) {
    //     e.preventDefault();
    //    $("#validation-success").html("<div class='k-messagebox k-messagebox-success'>Form data is valid!</div>");
    //}

    //function onFormClear(e) {
    //    $("#validation-success").html("");
    //}


    function getCompanyId() {
       
        return { CompanyId: $('#extension_39d2bd21d67b480891ffa985c6eb1398_CompanyId').val() };
    }

    function changeCompany(e) {
       
        $('#extension_39d2bd21d67b480891ffa985c6eb1398_CustomerNumber').data('kendoComboBox').dataSource.read();
    }

</script>

0
Dave
Top achievements
Rank 1
answered on 01 Jun 2020, 01:25 PM

Hi,

I have added your code to my project and the test throws the same error as my code.

Seems like it is an issue with my project.

This project was created with the trial version of the 2020 first release and then upgrade to the 20202 second release trial version.

Any ideas about what to check for?

Thanks,

DaveS

 

 

 

 

 

0
Dimitar
Telerik team
answered on 02 Jun 2020, 04:10 AM

Hello Dave,

Please make sure that the upgrade process was successful. To do this, verify that:

1) The script and style references of the new version are referenced in the _Layout.cshtml

2) The new Kendo.Mvc.dll version is referenced in the project References.1

If the above does not help, I would suggest opening a separate support thread where you can attach an isolated version of your solution so that I can inspect it further.

Regards,
Dimitar
Progress Telerik

Progress is here for your business, like always. Read more about the measures we are taking to ensure business continuity and help fight the COVID-19 pandemic.
Our thoughts here at Progress are with those affected by the outbreak.
0
Dave
Top achievements
Rank 1
answered on 03 Jun 2020, 04:47 PM

Layout:

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    <!--This bundle was moved by the Telerik VS Extensions for compatibility reasons-->
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/bootstrap")
    <link href="https://kendo.cdn.telerik.com/2020.2.513/styles/kendo.bootstrap-v4.min.css" rel="stylesheet" type="text/css" />
    <link href="https://kendo.cdn.telerik.com/2020.2.513/styles/kendo.common.min.css" rel="stylesheet" type="text/css" />
    <link href="https://kendo.cdn.telerik.com/2020.2.513/styles/kendo.default.min.css" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/Content/bootstrap.min.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="https://kendo.cdn.telerik.com/2020.2.513/js/jquery.min.js"></script>
    <script src="https://kendo.cdn.telerik.com/2020.2.513/js/jszip.min.js"></script>
    <script src="https://kendo.cdn.telerik.com/2020.2.513/js/kendo.all.min.js"></script>
    <script src="https://kendo.cdn.telerik.com/2020.2.513/js/kendo.aspnetmvc.min.js"></script>
    <script src="@Url.Content("~/Scripts/bootstrap.min.js")"></script>
    <script src="@Url.Content("~/Scripts/kendo.modernizr.custom.js")"></script>
</head>

BundleConfig.cs:

namespace CustomerPortal
{
    public class BundleConfig
    {
        // For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                      "~/Scripts/jquery.validate*"));


            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));
        }
    }
}

I added the jqueryvalidate and copied them into my Scripts directory.

Thanks,

DaveS

0
Dave
Top achievements
Rank 1
answered on 03 Jun 2020, 04:48 PM
ps same error
0
Dimitar
Telerik team
answered on 04 Jun 2020, 05:49 AM

Hello Dave,

I have reviewed the provided snippet but the information is not enough to diagnose the issue further. Generally speaking, there is no need including jquery validate script for the form validation to work.

Taking the above into consideration, the recommended approach is to send us an isolated solution where the described error can be replicated. I would suggest to modify the solution that I have sent earlier accordingly and then attach it here for further review.

Regards,
Dimitar
Progress Telerik

Progress is here for your business, like always. Read more about the measures we are taking to ensure business continuity and help fight the COVID-19 pandemic.
Our thoughts here at Progress are with those affected by the outbreak.
0
Dave
Top achievements
Rank 1
answered on 08 Jun 2020, 03:58 PM

Hi,

I attempted to create a solution for you to replicate the error unfortunately I end up with code that worked,

I created a new project and added your model, view and controller.

Went thru the upgrade process to the latest trial version and your form example works.

I did notice the html from new project is different than my project:

<input name="FirstName" title="FirstName" class="k-textbox" id="FirstName" aria-labelledby="FirstName-form-label" type="text" data-val-required="The FirstName field is required." autocomplete="off" data-val="true" data-bind="value:FirstName">

My failing project:

<input name="FirstName" title="FirstName" class="k-textbox" id="FirstName" aria-labelledby="FirstName-form-label" type="text" data-bind="value:FirstName">

Any suggestions?

Also I did not use Validation as the action on the post. Is that required? I assumed that was just how the actions were named in the example.

DaveS

 

 

 

 

 

0
Dimitar
Telerik team
answered on 09 Jun 2020, 05:02 AM

Hello Dave,

The difference in the html is due to the data validation attributes that are automatically applied (data-val-required data-val). These are generated based on the Model annotations. You can test this out by removing the "[Required]" annotations from the model. However, if the client validation is removed, the server validation still correctly displays.

I would suggest to make sure that:

1) There are no JavaScript errors being thrown when the page loads.

2) The form is correctly submitted when the "Submit" button is clicked.

3) The submit request hits the specified end-point on the server (where the ModelState errors are being set).

Regards,
Dimitar
Progress Telerik

Progress is here for your business, like always. Read more about the measures we are taking to ensure business continuity and help fight the COVID-19 pandemic.
Our thoughts here at Progress are with those affected by the outbreak.
0
Dave
Top achievements
Rank 1
answered on 10 Jun 2020, 12:44 PM

Hi,

I should have mentioned that the I know about the [Required] annotation and it was there in the failing project.

I was hoping this might give you a clue to what I and missing.

Thanks,

DaveS

0
Dimitar
Telerik team
answered on 11 Jun 2020, 07:41 AM

Hello Dave,

In order to continue my investigation on the matter, I will need a simple example that exhibits the issue. In case you manage to isolate such a sample, I will be happy to troubleshoot it further.

Regards,
Dimitar
Progress Telerik

Progress is here for your business, like always. Read more about the measures we are taking to ensure business continuity and help fight the COVID-19 pandemic.
Our thoughts here at Progress are with those affected by the outbreak.
Tags
Form
Asked by
Dave
Top achievements
Rank 1
Answers by
Dimitar
Telerik team
Dave
Top achievements
Rank 1
Share this question
or