【问题标题】:Issue when assigning values to Custom Model Binder将值分配给自定义模型绑定器时的问题
【发布时间】:2017-06-01 06:30:32
【问题描述】:

我得到了

在 *****Tests.dll 中发生了“System.NullReferenceException”类型的异常,但未在用户代码中处理

附加信息:对象引用未设置为对象的实例。

如何正确地为绑定模型赋值?

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

执行model.UserName = "test123@gmail.com";时出现异常

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

【问题讨论】:

  • 除非有必要,否则您通常不会测试控制器。

标签: c# asp.net-mvc model-binding custom-binding custom-model-binder


【解决方案1】:

您的RegisterBindingModel model 未初始化。

由于这个原因,未处理的空异常(对象引用未设置为对象的实例)。发生。

所以尝试类似:

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 = "test123@gmail.com";
        var result = ac.Register(model);
        Assert.AreEqual("User Registered Successfully", result);
    }

【讨论】:

    【解决方案2】:

    此错误消息有点神秘,但它表示您认为不是 null 的内容。

    RegisterBindingModel model; 没有实例。给它一个,它应该可以工作。如果仍然出错,请将所有内容包装在 try catch 中并进行调试。

    RegisterBindingModel model = new RegisterBindingModel();

    【讨论】:

      【解决方案3】:

      您声明了一个模型,但您没有初始化它以使其指向内存中的某个位置。尝试写作 RegisterBindingModel model = new RegisterBindingModel();

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-27
        • 1970-01-01
        • 1970-01-01
        • 2019-11-24
        相关资源
        最近更新 更多