为什么要获取 textboxfor null 异常?

Why get textboxfor null exception?

大家好,我是 ASP.NET MVC 初学者。 我按照课本例子练习ASP.NET MVC 但有错误!它显示空异常 ...

控制器:

namespace prjHelper.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(Member member)
        {
            string msg = "";
            msg = $"註冊資料如下:<br>" +
               $"帳號:{member.UserId}<br>" +
               $"密碼:{member.Pwd}<br>" +
               $"姓名:{member.Name}<br>" +
               $"信箱:{member.Email}<br>" +
               $"生日:{member.BirthDay.ToShortDateString()}";
            ViewBag.Msg = msg;
            return View(member);
        }
    }
}

型号:

namespace prjHelper.Models
{
    public class Member
    {
        public string UserId { get; set; }
        public string Name { get; set; }
        public string Pwd { get; set; }
        public string Email { get; set; }
        public DateTime BirthDay { get; set; }
    }
}

查看:

@model prjHelper.Models.Member

@{
    ViewBag.Title = "會員註冊";
}

<h2>會員註冊</h2>

@using (Html.BeginForm())
{
    <p>
        帳號:@Html.TextBoxFor(model => model.UserId,  new { @class = "form-control", required="required"})
    </p>
    <p>
        密碼:@Html.PasswordFor(m => m.Pwd,   new { @class = "form-control" })
    </p>
    <p>
        姓名:@Html.TextBoxFor(m => m.Name,   new { @class = "form-control" })
    </p>
    <p>
        信箱:@Html.TextBoxFor(m => m.Email,   new { @class = "form-control", type = "email" })
    </p>
    <p>
        生日:@Html.TextBoxFor(m => m.BirthDay,   new { @class = "form-control", type = "date" })
    </p>
    <p><input type="submit" value="註冊" class="btn btn-success" /></p>
    <hr />
    <p>@Html.Raw(@ViewBag.Msg)</p>
}

有人能帮我解释一下吗? 谢谢

如果你尽力了,你就不必担心失败。 精力和毅力征服一切。

您将视图数据模型描述为 @model prjHelper.Models.Member。但是在 public ActionResult Create() 方法中你创建了 View() 而没有传递数据模型。因此它是 null.

您使用 @model 定义了数据模型。它被称为强类型视图。因此,有必要创建 Memeber 对象实例并将其传递给如下视图:

public ActionResult Create()
{
    // Create the model that will be passed to the view for rendering.
    var model = new Member() { /* define properties */};

    // Now created `ViewResult` object for the response.
    return View(model);
}