【问题标题】:ASP.NET MVC Required DataAnnotationASP.NET MVC 所需的数据注解
【发布时间】:2013-05-06 15:50:03
【问题描述】:

我正在使用 ASP.NET 构建我的第一个应用程序,并且我正在使用 Entity Framework。

我有两个班级:

public class Owner
{
    public int ID { get; set; }
    [Required(ErrorMessage="Empty Owner name")]
    [MaxLength(10,ErrorMessage="Up to 10 chars")]
    [Display(Name="Owners name")]
    public string Name { get; set; }
    public DateTime Born { get; set; }
    public virtual List<Dog> dogs { get; set; }
}
public class Dog
{
    public int ID { get; set; }
    [Required(ErrorMessage="Empty dog name")]
    [MaxLength(10,ErrorMessage="Up to 10 chars")]
    [Display(Name="Dogs name")]
    public string Name { get; set; }
    public virtual Owner owner { get; set; }
}

我可以将所有者添加到数据库中,但我不能添加狗。 我在视图中使用文本框和列表框,例如:

@using (Html.BeginForm("New", "Dog"))
{
    @Html.LabelFor(x => x.Name);
    @Html.TextBoxFor(x => x.Name);
    <br />
    @Html.ListBoxFor(x => x.owner.ID, new MvcApplication2.Models.GazdiKutyaDB().GetOwners());
    <br />
    <input type="submit" />
}

我创建了一个GetOwners 方法来将现有所有者添加到列表框中,并为用户选择谁是狗的所有者。

public List<SelectListItem> GetOwners()
{
    List<SelectListItem> g = new List<SelectListItem>();
    foreach (Owner item in owners)
    {
         SelectListItem sli = new SelectListItem();
         sli.Text = item.Name;
         sli.Value = item.ID.ToString();
         g.Add(sli);
    }
    return g;
}

我为 Dogs 创建了一个控制器。这是我的添加方法:

[HttpGet]
public ActionResult New()
{            
     return View();
}
[HttpPost]
public ActionResult New(Dog k)
{
     if (ModelState.IsValid)
     {
          k.owner = (from x in db.owners
                      where x.ID == k.owner.ID
                      select x).FirstOrDefault();
          db.dogs.Add(k);
          db.SaveChanges();
          return RedirectToAction("Index", "Dog"); 
     }
     else
     {
          return View(k);
     }
}

我插入了断点,之所以ModelState.IsValid为假,是因为所有者名是空的:[Required(ErrorMessage="Empty Owner name")]这个我不明白,因为我想在那儿加一条狗。

【问题讨论】:

    标签: c# asp.net-mvc-4 ef-code-first data-annotations


    【解决方案1】:

    为什么不像这样将 ownerID 添加到类中:

    public class Dog
    {
        public int ID { get; set; }
        [Required(ErrorMessage="Empty dog name")]
        [MaxLength(10,ErrorMessage="Up to 10 chars")]
        [Display(Name="Dogs name")]
        public string Name { get; set; }
        public int ownerID { get; set; }
    }
    

    当您使用数据库时,这是最简单的方法(在我看来)。

    Here is an excellent video tutorial, showing ways to get your models to work as expected in EF

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多