Issue when assigning values to Custom Model Binder

109 views Asked by At

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; }
}
3

There are 3 answers

0
Ashiquzzaman On BEST ANSWER

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);
    }
0
robjam On

This error message is a little cryptic, but it says that something is null that you thought wasn't.

RegisterBindingModel model; doesn't have an instance. Give it one and it should work. If it still errors, wrap everything in a try catch and debug it.

RegisterBindingModel model = new RegisterBindingModel();

0
Din Serban On

You declared a model but you did not initialized it for it to point to some place in memory. Try writting RegisterBindingModel model = new RegisterBindingModel();