2
我想從html頁面上的dropdownList中獲取參數並將其發送到我的控制器,創建新的Model對象並將其插入到數據庫中。ModelState.isValid - false
這是我的控制器(兩種方法來創建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頁面上下拉列表:
@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設置爲此模型。但在Create
方法的結果,我有一個null musicStyles
,並且ModelState.isValid == false
嘗試添加'@ Html.ValidationSummary(假)'在你看來,看你遞交表格後得到的錯誤消息。 – ekad
@ekad我沒有消息 – Ales
閱讀此:http://stackoverflow.com/a/1791664/1905949 – ekad