dropdownlist的验证在mvc中不起作用 [英] Validation for dropdownlist doesn't work in mvc

查看:66
本文介绍了dropdownlist的验证在mvc中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用数据注释创建了一个表单进行验证。如果没有在下拉列表中进行选择;它应该验证表单。

控制器:

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; }

      }





查看





@using(Html.BeginForm())

{

@ Html.ValidationSummary(true)

{



专辑



View


@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
{

Album



@ Html.LabelFor(model => model.GenreId,Genre)


@Html.LabelFor(model => model.GenreId, "Genre")






@ Html.DropDownListFor(model => model.GenreId,ViewBag.GenreId as SelectList)

@ Html.ValidationMessageFor(model => model.GenreId)


@Html.DropDownListFor(model=>model.GenreId, ViewBag.GenreId as SelectList)
@Html.ValidationMessageFor(model => model.GenreId)






@ Html.LabelFor(model => model.ArtistId,Artist)


@Html.LabelFor(model => model.ArtistId, "Artist")






@ Html.ValidationMessageFor(model => model.ArtistId )


@Html.ValidationMessageFor(model => model.ArtistId)



}

}





验证d如果我没有从dropdwnlist中选择任何内容


}
}


validation doesn't work if i don't select anything from dropdwnlist

推荐答案

你可以查看以下链接来创建和显示mvc中的下拉列表:



使用MVC中的Dropdownlist



或者您也可以使用jQuery在MVC 5中显示下拉列表。请参阅以下链接:



使用MVC 5中的jQuery下拉列表
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


这篇关于dropdownlist的验证在mvc中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆