C# 为什么我的验证不起作用?asp.NETMVC
我试图在视图中放置一个C# 为什么我的验证不起作用?asp.NETMVC,c#,asp.net-mvc,validation,model-view-controller,C#,Asp.net Mvc,Validation,Model View Controller,我试图在视图中放置一个ValidationMessageFor来控制数据,但它不起作用,数据进入我的post操作 这是我的模型课: public enum CustomerType { JuridicalPerson, NaturalPerson } public class Customer { [Key] [DisplayName("ID")] public
ValidationMessageFor
来控制数据,但它不起作用,数据进入我的post操作
这是我的模型课:
public enum CustomerType
{
JuridicalPerson,
NaturalPerson
}
public class Customer
{
[Key]
[DisplayName("ID")]
public int CustomerId { get; set; }
[Required(ErrorMessage = "Please enter your first name")]
[DisplayName("First name")]
[DataType(DataType.Text)]
public string FirstName { get; set; }
[Required(ErrorMessage ="Please enter your last name")]
[DisplayName("Last name")]
[DataType(DataType.Text)]
public string LastName { get; set; }
[Required(ErrorMessage ="Please choose your customer type")]
[DisplayName("Customer type")]
public CustomerType CustomerType { get; set; }
下面是我的创建客户视图:
@model Contracts.Models.Customer
@using (Html.BeginForm())
{
<div class="box">
<div class="input-container">
@Html.LabelFor(model => model.FirstName)
<br />
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="input-container">
@Html.LabelFor(model => model.LastName)
<br />
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="input-container">
@Html.LabelFor(model => model.CustomerType)
<br />
@Html.EnumDropDownListFor(model => model.CustomerType, "Select a type", new {@class ="input-container" })
@Html.ValidationMessageFor(model => model.CustomerType)
</div>
<input class="btn" type="submit" value="Create" />
</div>
}
实际上,在我的视图中使用html助手验证时,空输入应该会给出一个错误,不会进入我的操作,但它不起作用
如果您能帮助我,我将不胜感激
if (ModelState.IsValid){
db.Customers.Add(customer);
db.SaveChanges();
return RedirectToAction("Index");} return Page();
您是否在使用客户端验证脚本,如非结构化jquery?它是通过布局页面或其他方式注入到您的视图中的吗?对不起,我是初学者。不,我没有使用任何脚本,除了我在布局页面中添加的一个scripts.render,用于在视图中添加css。我该怎么办?谢谢你,伙计,这很有效。谢谢你的帮助。
if (ModelState.IsValid){
db.Customers.Add(customer);
db.SaveChanges();
return RedirectToAction("Index");} return Page();