I'm trying to get to grips with the Validation messages in ASP.Net MVC. I have the following view
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<h2>Create User</h2>
<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>
<% using (Html.BeginForm()) {%>
<fieldset>
<legend>Fields</legend>
<p>
Username : <%= Html.TextBox("Username") %>
</p>
<p>
Forename : <%= Html.TextBox("Forename") %>
<%= Html.ValidationMessage("Forename", "*") %>
</p>
<p>
Surname : <%= Html.TextBox("Surname","") %>
<%= Html.ValidationMessage("Surname", "*") %>
</p>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%=Html.ActionLink("Back to List", "Index") %>
</div>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server">
<title><%= ViewData["ProjectTitle"] %> - Create User</title>
</asp:Content>
I then have this post method in my controller that is supposed to display an error message if the surname field is blank, I realise there is no other logic in this function im just trying to get my head round validation.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection formValues)
{
if (formValues["Surname"] == string.Empty)
ViewData.ModelState.AddModelError("Surname", "No way");
return View("Create");
}
When I run this and click to save a user the Create method runs fine and adds the error, but then the application falls over, it hightlights the line in the view that creates the surname textbox and says "Not set to an instance of object". It runs fine if I put something in the surname textbox and the error does not get added.
I'm guessing I'm missing something really simple but can work out what.
Any ideas?
Thanks
Gavin