tags:

views:

138

answers:

3

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

+1  A: 

Did you try to remove the second argument on TextBox? It will look for the empty key in ViewData.

the line below

Surname : <%= Html.TextBox("Surname","") %>

needs to be like

Surname : <%= Html.TextBox("Surname") %>
yapiskan
Yeah it needs to be <%= Html.TextBox("Surname") %>
RichardOD
This is how I had it at first, I changed it when I first got the error to see if that would fix it but it made no difference
Gavin Draper
hmm. interesting. it needs to give an object reference in this case. but could you try to change the validation control for forename field. remove the surname and try it for forename? does the same case occur?
yapiskan
by the way, you should remove the second argument.
yapiskan
If I change it in the controller to put the error on forename the same error occurs but it happens on the forename textbox instead
Gavin Draper
Hmm, I have no idea about what the problem is :/
yapiskan
A: 

I think I've found a solution adding the setModelValue line below to my method above the line that sets the error makes it work.

            ModelState.SetModelValue("Username", new ValueProviderResult(ValueProvider["Username"].AttemptedValue, formValues["Username"], System.Globalization.CultureInfo.CurrentCulture));
            ModelState.AddModelError("Username", "Invalid Username");

If anyone could explain why this works that would be great, If not I'll accept this answer tommorow. I'd rather not have to do this for ever field I validate unless I really have to.

Gavin Draper
A: 

You should test for Null or empty in your if statement,

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(string Username, string Surname,  string Forename)
{
  if (String.IsNullOrEmpty(Surname))
  {
     ModelState.AddModelError("Surname", "No way");
  }

  return View();
}
Tony Borf