我有一个非常简单的页面(我已经将它缩减到几乎没有,看看我是否可以正常工作)。使用如下所示的 lambda 调用 Html.TextBoxFor
时抛出 NullReferenceException。我想弄清楚这是为什么?
异常本身似乎已得到处理,因为它不会停止呈现页面,但我认为它根本不应该发生?文本框实际上按预期呈现正确(使用正则表达式和占位符)。
如果我将 TextBoxFor
换成 PasswordFor
,也不会抛出 NullReferenceException。
查看:
@model Analytics.Sites.Frontend.Models.RegisterViewModel
<div>
@using (Html.BeginForm("Register", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "centeralign", role = "form" }))
{
@Html.TextBoxFor(m => m.Email, new { @placeholder = "email@address.com" })
}
</div>
View 模型
public class RegisterViewModel
{
[Required]
[Display(Name = "Email")]
[DataType(DataType.EmailAddress)]
[RegularExpression(@"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", ErrorMessage = "The email address you entered is not valid.")]
public string Email { get; set; }
}
异常(exception):
System.NullReferenceException
at lambda_method(Closure , RegisterViewModel )
想法?这是设计使然,它在内部抛出并捕获 NullReferenceException 吗?
编辑:
Controller 本身是空的。
[Authorize]
public class AccountController : Controller
{
[AllowAnonymous]
public ActionResult Register()
{
return View();
}
}
显然,这不是将模型实例传递给 View 。更改为 return View(new RegisterViewModel)
将取消 NRE。这是这样做的预期方式吗?样本显示并非如此。
如果您使用 VS2013 创建一个新的框架 MVC 项目,它在帐户/注册方法上具有与此相同的代码。骨架项目也抛出(句柄?)相同的 NRE。这可能是设计使然?
最佳答案
您必须将模型的实例传递给 View :
public ActionResult Register()
{
return View(new RegisterViewModel());
}
这是MVC中的正确做法。如果没有模型实例,则无法访问模型的属性。
关于c# - Html.TextBoxFor NullReferenceException 使用 Razor 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22765412/