简体   繁体   中英

why my validation is not working? asp.net mvc

I tried to put a ValidationMessageFor in my view to control data but it's not working and data goes to my post action.

Here is my model class:

 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; }

and here is my create customer view:

@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>
}

and finally this is my customer controller and its action for create a customer:

 [HttpPost]
        public ActionResult Create(Customer customer)
        {
//db is my database context
            db.Customers.Add(customer);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

actually with html helper validation in my view,empty inputs should give an error and not goes to my action but is's not working

I'll appreciate if you help me

try using

if (ModelState.IsValid){
        db.Customers.Add(customer);
        db.SaveChanges();
        return RedirectToAction("Index");} return Page();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM