ASP.NET으로 첫 번째 앱을 제작하고 있으며 Entity Framework를 사용하고 있습니다.ASP.NET MVC 필수 DataAnnotation
나는 두 개의 클래스가 있습니다
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;
}
나는 개들을위한 컨트롤러를 만들었습니다. 여기에 내 추가하는 방법이다 : 나는 브레이크 포인트를 삽입
[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")]
내가 이것을 이해하지 않습니다.