Required Field Doesn't work for one field but does for other
I am using a standard validation with MVC, acrossed with my fluent nHibernate
[DisplayName("Product Name")]
[Required(ErrorMessage = "Product Name Required")]
public virtual string ProductName { get; set; }
[DataType(DataType.MultilineText)]
public virtual string Description { get; set; }
[DataType(DataType.Currency)]
[Required(ErrorMessage = "Price Required")]
public virtual decimal Price { get; set; }
[Required(ErrorMessage = "Quantity Required")]
[Range(0, 100000, ErrorMessage = "Must be postive number less then 100000")]
public virtual int Quantity { get; set; }
public virtual bool Live { get; set; }
public virtual ICollection<Attribute> Attribute { get; set; }
public virtual ICollection<Images> Images { get; set; }
This is what makes up my "Product" class... for some reason the name doesnt validate as a required field but things like quantity and Price do.
View has these in it
<tr>
<td>
<%= Html.LabelFor(model => model.ProductName)%>
</td>
<td>
<%= Html.TextBoxFor(model => model.ProductName, new { @class = "txt" })%>
<%= Html.ValidationMessageFor(model => model.ProductName)%>
</td>
</tr>
and this bit works fine
<tr>
<td>
<%= Html.LabelFor(model => model.Pri开发者_如何学JAVAce) %>
</td>
<td>
<%= Html.TextBoxFor(model => model.Price, String.Format("{0:F}", Model.Price)) %>
<%= Html.ValidationMessageFor(model => model.Price) %>
</td>
</tr>
And this is the controller as asked for
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddProduct(Product NewProduct)
{
if (ModelState.IsValid)
{
var ProductRepository = GetRepository<Product>();
ProductRepository.Add(NewProduct);
return Redirect("/");
}
return View(NewProduct);
}
Just give it a try:
[DisplayName("Product Name")]
[Required(ErrorMessage = "Product Name Required", AllowEmptyStrings = false)]
public virtual string ProductName { get; set; }
i found that it was a isssue with not setting the data type
[DataType(DataType.Text)]
Was missing from my ProductName field!
精彩评论