我使用自动生成的实体模型类,然后我使用带有元数据的分部类来对自动生成的类进行验证,如下所示。
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();
}
}
}发布于 2015-09-05 04:22:28
为了使分部类工作,两个分部必须具有相同的命名空间。您不必在文件结构中移动实际的文件,只需编辑tblDepartmentCustom的名称空间以匹配tblDepartmentMaster的名称空间即可。
https://stackoverflow.com/questions/32374613
复制相似问题