我正在使用 EF + MVC3 + razor 我有我的 userProfile 模型类,其中包含名称、姓氏变量 + 外键爱好(因为我想将其视为下拉列表)我创建了一个控制器,只需选择这个类和数据上下文。
当我尝试创建记录时,它不允许我,因为它在验证区域中说:“爱好字段是必需的。”。我希望不需要“爱好”下拉菜单。我怎样才能做到这一点?!..
这就是我所拥有的:
模型:
public class UserProfile {
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Surname { get; set; }
public int HobbiesId { get; set; }
public virtual Hobby Hobby { get; set; }}
public class Hobby
{
public int HobbiesId { get; set; }
public string HobbieName { get; set; }
public virtual ICollection<UserProfile> UserProfiles { get; set; }
}
public class UserProfileDBContext : DbContext
{
public DbSet<UserProfile> UserProfiles { get; set; }
public DbSet<Hobby> Hobbies{ get; set; }
}
看法:
[..]@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>UserProfile</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Surname)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Surname)
@Html.ValidationMessageFor(model => model.Surname)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.HobbyId, "Hobby")
</div>
<div class="editor-field">
@Html.DropDownList("HobbyId", String.Empty)
@Html.ValidationMessageFor(model => model.HobbyIdId)
</div>
[..]
控制器的创建是:
[HttpPost]
public ActionResult Create(UserProfile userprofile)
{
if (ModelState.IsValid)
{
db.UserProfiles.Add(userprofile);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.HobbyId = new SelectList(db.Hobbies, "HobbyId", "Hobby", userprofile.HobbyId);
return View(userprofile); }
我已经尝试修改:
public class Hobby
{
public int ?HobbiesId { get; set; }
但它没有用。
有什么帮助吗?...
提前致谢!..
即插即用