Search code examples
c#asp.net-mvcmodel-bindingcustom-bindingcustom-model-binder

Issue when assigning values to Custom Model Binder


I am getting

An exception of type 'System.NullReferenceException' occurred in *****Tests.dll but was not handled in user code

Additional information: Object reference not set to an instance of an object.

How to correctly assign values to the binding model?

public class PersonRegistration
{
    RegisterBindingModel model;
    [TestMethod]
   
    public void TestMethod1()
    {
        AccountController ac = new AccountController(userManager, loggingService);
        model.UserName = "[email protected]";
        var result = ac.Register(model);
        Assert.AreEqual("User Registered Successfully", result);
    }

I am getting the exception when executing model.UserName = "[email protected]";

public class RegisterBindingModel
{
    public RegisterBindingModel();
    [Display(Name = "User name")]
    [Required]
    public string UserName { get; set; }
}

Solution

  • Your RegisterBindingModel model not initialized.

    For this reason unhandled null exception (Object reference not set to an instance of an object).occurred.

    So try something like:

    public class RegisterBindingModel
    {   
        [Display(Name = "User name")]
        [Required]
        public string UserName { get; set; }
    }
    
    public class PersonRegistration
    {
        RegisterBindingModel model= new RegisterBindingModel ();//initialized
        [TestMethod]
    
        public void TestMethod1()
        {
            AccountController ac = new AccountController(userManager, loggingService);
            model.UserName = "[email protected]";
            var result = ac.Register(model);
            Assert.AreEqual("User Registered Successfully", result);
        }