whodares
whodares

Reputation: 696

mvc model validation required not working on all fields

I'm working in ASP.NET MVC 4 and I have the problem that my model validation isn't working correctly. For some reason not all my required fields have to be filled in.

Here's my model:

public class MovieModel
    {
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }
        public DateTime ReleaseDate { get; set; }
        [Required]
        public string Genre { get; set; }
        [Required]
        public decimal Price { get; set; }

        public virtual ICollection<RoleInMovie> RoleInMovie { get; set; }
    }

Here's the View:

@using (Html.BeginForm())
{
    <table>
        <tr>
            <td>
                <label>Name:</label></td>
            <td>@Html.EditorFor(m => m.Name)</td>
            <td>@Html.ValidationMessageFor(m => m.Name)</td>
        </tr>
        <tr>
            <td>
                <label>Genre:</label></td>
            <td>@Html.EditorFor(m => m.Genre)</td>
            <td>@Html.ValidationMessageFor(m => m.Genre)</td>
        </tr>
        <tr>
            <td>
                <label>Price:</label></td>
            <td>@Html.EditorFor(m => m.Price)</td>
            <td>@Html.ValidationMessageFor(m => m.Price)</td>
        </tr>
    </table>
    <button type="submit">Submit</button>
}

And here's my action:

[HttpPost]
        public ActionResult Add(MovieModel model)
        {
            if(ModelState.IsValid)
            {
                return RedirectToAction("Index");
            }
            return View();
        }

Now here's the thing: as soon as I enter only a price, modelstate.isvalid becomes true. When hovering over my model, it sais both name and genre are null. Ofcourse they are required, but the validation doesn't work. Also, the validationmessagefor only works on price.

I hope I'm not overlooking something too ridiculous. Thanks for the help!

Upvotes: 2

Views: 20355

Answers (1)

asawyer
asawyer

Reputation: 17808

Return the invalid model back to the view:

[HttpPost]
public ActionResult Add(MovieModel model)
{
    if(ModelState.IsValid)
    {
        return RedirectToAction("Index");
    }
    return View(model); // <----
}

Oh, and make sure that the required attribute is disallowing empty strings

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.requiredattribute.allowemptystrings.aspx

public class MovieModel
{
    public int Id { get; set; }

    [Required(AllowEmptyStrings = false)]
    public string Name { get; set; }

    public DateTime ReleaseDate { get; set; }

    [Required(AllowEmptyStrings = false)]
    public string Genre { get; set; }

    [Required]
    public decimal Price { get; set; }

    public virtual ICollection<RoleInMovie> RoleInMovie { get; set; }
}

Upvotes: 15

Related Questions