I following this tutorial for MVC data validation: http://www.tutorialsteacher.com/mvc/implement-validation-in-asp.net-mvc and somehow this is not working. Below is my code:
Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace LayoutProject.Models
{
public class Book
{
[Required]
public int bookId { get; set; }
[Required]
public String title { get; set; }
[StringLength(50)]
public String author { get; set; }
[Range(0,4)]
public int publicationYear { get; set; }
public String editor { get; set; }
}
}
Partial View:
@model LayoutProject.Models.Book
<h4>Books</h4>
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(b => b.bookId)
<table>
<tr>
<td>@Html.LabelFor(d=>d.bookId)</td>
<td>@Html.TextBoxFor(d=>d.bookId)
@Html.ValidationMessageFor(b => b.bookId, "", new { @class = "text-danger" })
</td>
</tr>
<tr>
<td>@Html.LabelFor(d=>d.title)</td>
<td>@Html.TextBoxFor(d=>d.title)</td>
</tr>
<tr>
<td>@Html.LabelFor(d=>d.author)</td>
<td>@Html.TextBoxFor(d=>d.author)</td>
</tr>
<tr>
<td>@Html.LabelFor(d=>d.publicationYear)</td>
<td>@Html.TextBoxFor(d=>d.publicationYear)</td>
</tr>
<tr>
<td>@Html.LabelFor(d=>d.editor)</td>
<td>@Html.TextBoxFor(d=>d.editor)</td>
</tr>
</table>
View:
@{
ViewBag.Title = "CreateBooks";
}
<h2>CreateBooks</h2>
<form action="/Home/SaveBooks" method="post">
@Html.Partial("_CreateBook")
<input id="createBook" type="submit" value="Submit"/>
</form>
As you can see, the bookId is a required field, however when I click on the submit button without entering any bookId, I get no error message. The model would go to the controller and follow any methods written there. Any idea what I might have missed?
Controller:
[HttpPost]
public ActionResult SaveBooks(Book book)
{
return View(book);
}
bookIdis typeofintwhich has a defaut value of0which means it has a value when your submit because of your hidden input (its notnull) so therefore is validbookid, it will be ignored because your hidden input is bound to the value and the textbox value is ignored by theDefaultModelBinder(only the value of the first input is bound)