随机整数的空引用

时间:2015-11-28 20:29:55

标签: c# asp.net-mvc

我有一个ViewModel,它有两个值(Val1和Val2),我用它来进行联系表单中的简单现实测试。

public class ContactFormViewModel
{
    private Random Random { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string EmailAddress { get; set; }
    public string Message { get; set; }
    public int Val1 => Random.Next(1, 9);
    public int Val2 => Random.Next(6, 19);
}

我尝试在这样的视图中使用它。

@model TraderToolkit.WebUI2.Models.EmailViewModels.ContactFormViewModel
//parts removed for brevity
@using (Html.BeginForm())
{
<div class="container">
   <div class="form-group">
      <form role="form" action="" method="post" id="registrationForm">
       //parts removed for brevity
           <label for="RealTest">What is <span id="val1">@Model.Val1</span> +    <span id="val2">@Model.Val2</span>? </label>
           <div class="input-group">
               <input type="text" class="form-control" name="RealTest" id="RealTest" required>
               <span class="input-group-addon"><i class="glyphicon glyphicon-ok form-control-feedback"></i></span>
           </div>
        </div>
        <button type="submit" class="btn btn-primary hidden" id="Send" name="Send" value="Send"></button>
        </div>
     </form>
   </div>
</div>
}

运行父亲并单击联系人表单时出现的错误是空引用异常,而不是设置为对象的实例。这是有道理的,因为班级永远不会“新”起来。由于我是MVC的新手,这可能在视图中吗?如果不是,我如何实例化这个类,以便我可以在视图中访问Val1和Val2?

感谢HaukurHaf的解决方案

更新模型

 public class ContactFormViewModel
{

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string EmailAddress { get; set; }
    public string Message { get; set; }
    public int Val1 { get; set; }
    public int Val2 { get; set; }

    public ContactFormViewModel()
    {
        var rnd = new Random();
        Val1 = rnd.Next(1, 9);
        Val2 = rnd.Next(6, 19);
    }
}

1 个答案:

答案 0 :(得分:0)

尝试定义默认构造函数并初始化那里的随机整数:

public class ContactFormViewModel
{
    private Random Random { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string EmailAddress { get; set; }
    public string Message { get; set; }
    public int Val1 { get; set; }
    public int Val2 { get; set; }

    public ContactFormViewModel()
    {
        Val1 = Random.Next(1,9);
        Val2 = Random.Next(6,19);
    }
}