0

Hey guys, I'm ASP.NET MVC beginner. I practice according to the textbook example ASP.NET MVC but got error!! It show null exception ...

Controller :

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

Model :

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

View:

@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>
}

Can anybody explain it for me? Thanks.

If you are doing your best, you will not have to worry about failure. Energy and persistence conquer all things.

Jackdaw
  • 7,626
  • 5
  • 15
  • 33
Stephen
  • 23
  • 2

1 Answers1

0

You described the view data model as @model prjHelper.Models.Member. But in the public ActionResult Create() method you created View() without passing the data model. Therefore it's null.

You are defined the data model by using @model. It's called strongly typed view. Therefore it's necessary to create the Memeber object instance and pass it to the view like below:

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);
}
Jackdaw
  • 7,626
  • 5
  • 15
  • 33