asp.net-mvc - 没有为此对象定义无参数构造函数?

标签 asp.net-mvc asp.net-mvc-3 razor

我在 POST 表单时遇到上述错误,我认为错误的根本原因是“DropDownListFor”,其中复数 SelectList 被调用两次,如果是,请提出解决方案?

如果我从“x=>x.Values”更改为“x=>x.Name”,则会收到错误“不存在具有键“DDLView.Name”的“IEnumerable”类型的 ViewData 项。”

编辑器模板

@model DropDownListViewModel

@Html.LabelFor(x=>x.Values, Model.Label)
@Html.DropDownListFor(x=>x.Values, Model.Values)

查看模型

public class HomePageViewModel
{
    public DropDownListViewModel DDLView { get; set; }
}

public class DropDownListViewModel
{
    public string Label { get; set; }
    public string Name { get; set; }
    public SelectList Values { get; set; }
}

Controller

public ActionResult Index()
    {
        HomePageViewModel homePageViewModel = new HomePageViewModel();

        homePageViewModel.DDLView = new DropDownListViewModel
                                        {
                                            Label = "drop label1",
                                            Name = "DropDown1",
                                            Values = new SelectList(
                                                         new[]
                                                             {
                                                                 new {Value = "1", Text = "text 1"},
                                                                 new {Value = "2", Text = "text 2"},
                                                                 new {Value = "3", Text = "text 3"},
                                                             }, "Value", "Text", "2"
                                                         )
                                        };
}

[HttpPost]
    public ActionResult Index(HomePageViewModel model)
    {
        return View(model);
    }

查看

@model Dynamic.ViewModels.HomePageViewModel
@using (Html.BeginForm())
{
@Html.EditorFor(x=>x.DDLView)


<input type="submit" value="OK" />

}

最佳答案

问题是 SelectList 没有无参数构造函数,并且模型绑定(bind)器无法实例化它,但您正尝试将其发回。

要解决您的问题,请在实现中更改两件事:

1) 更改编辑器模板

 @Html.DropDownListFor(x=>x.Values, Model.Values) 

 @Html.DropDownListFor(x=>x.ValueId, Model.Values) 

2) 添加到原始 DropDownListViewModel

[ScaffoldColumn(false)]
public string ValueId { get; set; }

现在您的操作后参数将填充正确的值。

关于asp.net-mvc - 没有为此对象定义无参数构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11439212/

相关文章:

asp.net-mvc - virtual 关键字、Include 扩展方法、延迟加载、预先加载——加载相关对象实际上是如何工作的

c# - 如何在 ASP.NET MVC2 中向 Controller 添加自定义 Hook

asp.net-mvc-3 - 如何将 asp.net MVC 脚手架与从 dbcontext 向下两个子类的上下文一起使用

c# - MVC 不验证空字符串

c# - MVC C# nameof() 部分添加 @Html.Hidden 未按预期工作

c# - 将数组传递给 ASP.NET Core 中的数据属性

c# - Identity UpdateAsync 丢失 IdentityResult.Failed

c# - 解决 .Net core 2.0 中抽象类的依赖注入(inject)

asp.net-mvc-3 - 禁用浏览器中的表单字段保存、自动完成功能

asp.net-mvc-3 - MVC 3 ASP.NET 角色-授权属性