【发布时间】:2014-01-24 21:54:37
【问题描述】:
我有一个奇怪的错误。 我使用 SQL Server Management Studio 创建了数据库。所有主键、外键、唯一集和工作。
我将数据库导入 mvc 项目并生成模型、控制器和视图,所有这些都与本教程中的一样:click
但由于未知原因,内置验证仅适用于外键!即使所有其他验证规则都是由 Visual Studio 搭建的。
不知道我应该提供什么代码,所以请随意提问,我会更新我的问题。
例如:创建用户:
@model magazyn.Models.User
@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>User</h4>
<hr />
@Html.ValidationSummary(true)
<div class="form-group">
@Html.LabelFor(model => model.EmployeeNo, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.EmployeeNo)
@Html.ValidationMessageFor(model => model.EmployeeNo)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Surname, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Surname)
@Html.ValidationMessageFor(model => model.Surname)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ContactInfo, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ContactInfo)
@Html.ValidationMessageFor(model => model.ContactInfo)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.RoleId, "RoleId", new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("RoleId", String.Empty)
@Html.ValidationMessageFor(model => model.RoleId)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
控制器:
public ActionResult Create()
{
ViewBag.RoleId = new SelectList(db.Roles, "Id", "RoleName");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
[UserEditAuth]
public ActionResult Create([Bind(Include="Id,EmployeeNo,Name,Surname,ContactInfo,RoleId")] User user)
{
if (ModelState.IsValid)
{
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.RoleId = new SelectList(db.Roles, "Id", "RoleName", user.RoleId);
return View(user);
}
和用户实体(由entityFramework生成):
public partial class User
{
public User()
{
this.DeviceUsages = new HashSet<DeviceUsage>();
}
public int Id { get; set; }
public string EmployeeNo { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string ContactInfo { get; set; }
public int RoleId { get; set; }
public virtual ICollection<DeviceUsage> DeviceUsages { get; set; }
public virtual Role Role { get; set; }
}
在这种情况下,仅验证角色,因为它是来自其他表的外键
【问题讨论】:
-
将有助于获得视图之一(即创建视图)、控制器操作和实体之一的源代码...
-
好的。添加了此操作中使用的视图、控制器操作和实体
标签: c# asp.net-mvc