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.

2 Answers 2

3

Your Create method is trying to construct a new CategoryPageViewModel from the posted form collection.

public ActionResult Create(CategoryPageViewModel categoryModel){...}

However, as your form only contains an input for CategoryName, your controller method cannot create a new CategoryPageViewModel where id is required.

You have two solutions to your problem:

  1. Make the Id in CategoryPageViewModel nullable as @Andrew mentioned.

    public int? Id { get; set; }
    
  2. Recommended Solution: Keep the Id as not nullable, but render this value in your form as a hidden input. This will allow you to keep your system Id intact from controller to view and back again.

    In the view add the Id as a hidden input using the following:

    <%= Html.Hidden("Id") %>
    
Sign up to request clarification or add additional context in comments.

Comments

0

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?

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.