0
我正在使用自動生成的實體模型類,比我用部分類與元數據將驗證放在自動生成的類,如下所示。即使自定義類實現自動化實體模型始終爲真
public class tblDepartmentCustom
{
[Key]
public int DepartmentId { get; set; }
[Required(ErrorMessage = "Department name is required")]
public string DepartmentName { get; set; }
}
[MetadataType(typeof(tblDepartmentCustom))]
public partial class tblDepartmentMaster
{
}
,是由實體框架生成的原始類在下面給出。
public partial class tblDepartmentMaster
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public tblDepartmentMaster()
{
this.tblDesignationMasters = new HashSet<tblDesignationMaster>();
}
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<tblDesignationMaster> tblDesignationMasters { get; set; }
}
所以這裏的問題是,每當我嘗試驗證模型狀態它出來是true.below是代碼。
@model EmployeeManager.Models.tblDepartmentCustom
@{
ViewBag.Title = "InsertDepartment";
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}<div class="col-md-4">
@using (Html.BeginForm("InsertDepartment", "Departments", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<span class="error-class">@ViewBag.FoundError</span>
<br />
<label>Department Name</label>
@Html.TextBoxFor(m => m.DepartmentName, new { @class = "form-control" })
<br />
<input type="submit" class="btn btn-info" value="Add Department" />
}
</div>
而下面的操作。
[HttpGet]
public ActionResult InsertDepartment()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
[ActionName("InsertDepartment")]
public ActionResult InsertDepartmentPost()
{
using (PMSEntities dc = new PMSEntities())
{
tblDepartmentMaster dm = new tblDepartmentMaster();
TryUpdateModel(dm);
if(ModelState.IsValid)
{
dc.tblDepartmentMasters.Add(dm);
dc.SaveChanges();
return View("_Success");
}
else
{
ViewBag.FoundError = "Department name is required.";
return View();
}
}
}
ModelState.IsValid-始終返回true,當提交空文本框時,它不會發生錯誤。 – techsolver
確保包含驗證屬性的類與生成的類具有相同的名稱空間。 – JB06
它們位於不同的文件夾/名稱空間中,因爲EF在根中自動生成,而我的自定義文件位於模型文件夾中。並告訴我在哪裏定義任何其他驗證屬性,我粘貼了以上所有代碼@ JB06 – techsolver