ViewModel中的ASP.NET MVC SelectList [英] ASP.NET MVC SelectList in ViewModel
问题描述
我正在ASP.NET MVC 5中工作(但这很可能也适用于以前的版本).提出此问题的最佳方法是向您显示代码:
I'm working in ASP.NET MVC 5 (but this most likely applies to previous versions also). Best way to ask this question is to show you the code:
这是视图模型:
public class PersonCreateViewModel
{
public SelectList cities {get; set;}
public String Name { get; set; }
public String Address { get; set; }
}
这是控制器的http Post方法:
Here is the http Post method from the controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(PersonCreateViewModel viewmodel)
{
if (ModelState.IsValid)
{
//Add to database here and return
}
//return back to view if invalid db save
return View(person);
}
这里是视图:
<div class="form-group">
@Html.LabelFor(model => model.person.name, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.person.name)
@Html.ValidationMessageFor(model => model.person.name)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.person.address, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.person.address)
@Html.ValidationMessageFor(model => model.person.address)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.person.CityID, "CityID", new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("cities")
@Html.ValidationMessageFor(model => model.person.CityID)
</div>
</div>
当用户单击提交时,浏览器中将显示以下错误消息: 没有为此对象定义无参数的构造函数."
When the user clicks submit, the following error message is in the browser: "No parameterless constructor defined for this object. "
我认为这与我的ViewModel中有一个SelectList有关.我认为,当视图在表单提交时将模型传递回控制器时,它将调用SelectList的构造函数,但是SelectList没有无参数的构造函数.我不确定如何进行.任何帮助表示赞赏!
I think it has something to do with the fact that I have a SelectList in my ViewModel. I think when the view passes the model back to the controller on form submission, it calls the constructor for the SelectList, but there is no parameterless constructor for SelectList. I'm not sure how to proceed. Any help is appreciated!!
推荐答案
我一直使用IEnumerable运气更好
I've always had better luck using IEnumerable
public class PersonCreateViewModel
{
public IEnumerable<SelectListItem> cities {get; set;}
public int CityId { get; set; }
public String Name { get; set; }
public String Address { get; set; }
}
此外,您将需要在视图模型上具有一个属性以捕获选定的值,例如CityId.
Also, you are going to need a property on the view model to capture the selected value like CityId.
然后您可以使用:
Html.DropDownListFor(m => m.CityId, Model.cities)
这篇关于ViewModel中的ASP.NET MVC SelectList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!