views:

90

answers:

1

I am trying to use the validation capability of ASP.NET MVC 2 (RC)

I have a

viewmodel

public class CategoryPageViewModel
{

            public int Id { get; set; }

            [Required(ErrorMessage="Category name required")]
            public string CategoryName { get; set; }
}

action

    [HttpPost()]
    public ActionResult Create(CategoryPageViewModel categoryModel)
    {
        if (ModelState.IsValid)
        {
            return View("Completed");
        }
        return View(categoryModel);

    }

view

<%= Html.ValidationSummary() %>

<% using (Html.BeginForm("Create", "Category", FormMethod.Post)) {%>

    <fieldset>
        <legend>Create new category</legend>
        <p>
            <label for="CategoryName">Category name:</label>
            <%= Html.TextBox("CategoryName") %>
            <%= Html.ValidationMessage("CategoryName", "*")%>
        </p>

        <p class="submit">
            <input type="submit" value="Create" />
        </p>
    </fieldset>

<% } %>

On submit it says the id field is also required but I have not set the Required attribute.

What am I doing wrong or is it a bug? This is the RC release downloaded today 26/12/09.

A: 

If you don't want to pass in the Id, make it nullable ... i.e.:

public class CategoryPageViewModel
{
            public int? Id { get; set; }

            [Required(ErrorMessage="Category name required")]
            public string CategoryName { get; set; }
}

or don't include it at all. How do you expect to perform any type of database update without an ID though?

Andrew
Id will be auto generated by db. Id will be required only when editing a category or assigning a category to another related object.
eb