gpt4 book ai didi

c# - ModelState.isValid - 错误

转载 作者:行者123 更新时间:2023-11-30 21:57:05 26 4
gpt4 key购买 nike

我想从 html 页面上的 dropdownList 获取参数并将其发送到我的 Controller ,创建新的模型对象,并将其插入数据库。

这是我的 Controller (创建 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 musicStylesModelState.isValid == false

最佳答案

A <select>仅回发一个值 - 它无法绑定(bind)到属性 List<MusicStyle> musicStyles您需要一个具有可以绑定(bind)到的属性的 View 模型

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

在 Controller 中

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

在 View 中

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

关于c# - ModelState.isValid - 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30964919/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com