【问题标题】:Data annotation is working on editing only数据注释仅用于编辑
【发布时间】:2011-08-03 14:52:05
【问题描述】:
Here is my controller codes

//
        // GET: /Department/Create

        public ActionResult Create()
        {
            return View(new department());
        } 

        //
        // POST: /Department/Create

        [HttpPost]
        public ActionResult Create(department dept)
        {
            try
            {
                dbContext.AddTodepartments(dept);
                dbContext.SaveChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Department/Edit/5

        public ActionResult Edit(int id)
        {
            return View(dbContext.departments.Single(d => d.DeptID == id));
        }

        //
        // POST: /Department/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            var dept = dbContext.departments.Single(d => d.DeptID == id);
            try
            {
                UpdateModel(dept);
                dbContext.SaveChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View(dept);
            }
        }

Here is the partial class 

    [MetadataType(typeof(DepartmentMetaData))]
    public partial class department
    {
    }
    public class DepartmentMetaData
    {
        [Required(AllowEmptyStrings = false, ErrorMessage = "Department name required.")]
        public string DeptName { get; set; }
    }


    The required field validation is happening on the editing only. I can insert a null 'Department name' but on eding the values, it is not allowing to enter a null value.

【问题讨论】:

    标签: asp.net-mvc data-annotations


    【解决方案1】:

    您应该在创建记录时检查ModelState.IsValid。更多关于 ModelState here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-06
      • 1970-01-01
      • 1970-01-01
      • 2012-05-30
      • 1970-01-01
      相关资源
      最近更新 更多