I am building my first app with ASP.NET, and I am using Entity Framework.
I have two classes:
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; }
}
I can add owners to the database, but I cannot add dogs. I am using a textbox and a listbox in the View like:
@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" />
}
I created a GetOwners method to add the existing owners to a listbox, and for the user, to select who is the owner of the dog.
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;
}
I created a Controller for the Dogs. Here is my adding method:
[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);
}
}
I inserted breakpoints, and the reason why ModelState.IsValid is false, is that the owners name is empty: [Required(ErrorMessage="Empty Owner name")] I don't understand this, because I want to add a dog there.