I have created one form for validation using data annotations.If no delection made in dropdownlist ;it should validate form.
controller:
public ActionResult Create()
{
ViewBag.GenreId = new SelectList(objdata.Genres, "GenreId","Name");
ViewBag.ArtistId = new SelectList(objdata.Artists, "ArtistId", "Name");
return View();
}
[HttpPost]
public ActionResult Create(Album album)
{
if (ModelState.IsValid)
{
objdata.Albums.Add(album);
/// Another way
// objdata.Entry(album).State = EntityState.Added;
objdata.SaveChanges();
return RedirectToAction("Index");
// return View(album);
}
return View(album);
}
model
public class Album
{
[DisplayName("Genre")]
[Required(ErrorMessage = "pls select Genre")]
public int GenreId { get; set; }
[DisplayName("Artist")]
[Required(ErrorMessage = "pls select Artist")]
public int ArtistId { get; set; }
}
View
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
{
Album
@Html.LabelFor(model => model.GenreId, "Genre")
@Html.DropDownListFor(model=>model.GenreId, ViewBag.GenreId as SelectList)
@Html.ValidationMessageFor(model => model.GenreId)
@Html.LabelFor(model => model.ArtistId, "Artist")
@Html.ValidationMessageFor(model => model.ArtistId)
}
}
validation doesn't work if i don't select anything from dropdwnlist