I'm just trying to do some simple validation in MVC RC and am getting an error. For the purposes of this question, I am not using the UpdateModel.
Here is the code in the form:
<%= Html.TextBox("UserId")%>
<%= Html.ValidationMessage("UserId") %>
If I add the following line in the controller, I will get a NullReferenceException on the TextBox:
ModelState.AddModelError("UserId", "*");
So to fix this, I've also added the following line:
ModelState.SetModelValue("UserId", ValueProvider["UserId"]);
Why am I having to rebind the value? I only have to do this if I add the error, but it seems like I shouldn't have to do this. I feel like Im doing something incorrectly or just not familiar enough with binding.
It looks like Im not the only one who has seen this. Per request, here is the controller code:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection)
{
AppUser newUser = new AppUser();
try
{
newUser.UserId = collection["UserId"];
AppUserDAL.AddUser(newUser);
return RedirectToAction("Index");
}
catch (Exception ex)
{
ViewData["ReturnMessage"] = ex.Message;
ModelState.AddModelError("UserId", "*");
ModelState.SetModelValue("UserId", ValueProvider["UserId"]);
return View(newUser);
}