ModelState.isValid - false

时间:2015-06-21 13:15:53

标签: c# asp.net asp.net-mvc entity-framework

我想从html页面的dropdownList获取参数并将其发送到我的控制器,创建新的Model对象,然后将其插入到数据库中。

这是我的控制器(创建My_Model的两种方法):

public ActionResult Create()
    {
        IEnumerable<MusicStyle> musicStyleList = db.MusicStyles.ToList();
        ViewData["musicStyles"] = new SelectList(musicStyleList);
        return View();
    }

    // POST: Bands/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "id,name,info,appearanceDate,musicStyles")] Band band)
    {
        IEnumerable<MusicStyle> musicStyleList;
        if (ModelState.IsValid)
        {
            musicStyleList = db.MusicStyles;
            ViewData["musicStyles"] = new SelectList(musicStyleList).ToList();
            db.Bands.Add(band);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        musicStyleList = db.MusicStyles;
        ViewData["musicStyles"] = new SelectList(musicStyleList).ToList();
        return View(band);
    }

这是我在html页面上的dropdownList:

@Html.DropDownList("musicStyles", "select style")

这是我的模特:

 public class Band
{
    [Required]
    public int id { get; set; }

    [Required]
    [RegularExpression(@"^[a-zA-Z-\s\\\/*_]+$")]
    [StringLength(60, MinimumLength = 1)]
    public string name { get; set; } 

    public string info { get; set; }

    [Required]
    [Display(Name = "Appearance date")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime appearanceDate { get; set; }

    public List<MusicStyle> musicStyles { get; set; }
    public List<Song> songs { get; set; }
    public List<Album> albums { get; set; }
}

它有一个musicStyles列表(引用多对多),我想将dropdownList中的selected元素设置为此模型。但是在Create方法的结果中,我有null musicStylesModelState.isValid == false

1 个答案:

答案 0 :(得分:3)

<select>只发回一个值 - 它无法绑定到属性List<MusicStyle> musicStyles您需要一个包含可绑定属性的视图模型

public class BandVM
{
  [Display(Name = "Music style")]
  [Required(ErrorMessage = "Please select a style")]
  public string SelectedMusicStyle { get; set; }
  public SelectList MusicStyleList { get; set; }
  ....
}

在控制器中

public ActionResult Create()
{
  BandVM model = new BandVM();
  model.MusicStyleList = new SelectList(db.MusicStyles);
  return View(model);
}

在视图中

@Html.LabelFor(m => m.SelectedMusicStyle)
@Html.DropDownListFor(m => m.SelectedMusicStyle, Model.MusicStyleList, "select style")
@Html.ValidationMessageFor(m => m.SelectedMusicStyle)

在POST方法中

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(BandVM model) // NO Bind.Include!
{
  // model.SelectedMusicStyle will contain the selected value
  // Create a new instance of the data model and map the view model properties to it
  // Save and redirect
}