Click here to Skip to main content
15,896,063 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have created one form for validation using data annotations.If no delection made in dropdownlist ;it should validate form.
controller:
SQL
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
SQL
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
Posted

1 solution

You can check out the following link to create and show the dropdownlist in mvc:

Working with Dropdownlist in MVC

Or you can also show the dropdownlist in MVC 5 using jQuery. Refer the following link:

Dropdownlist using jQuery in MVC 5
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900