2012-07-11 81 views
3

我得到了上面承受错误,而POST形式,我认为受到错误的根本原因是“DropDownListFor”,其中多次SelectList两次调用,如果是的,请提出解决方案?没有为此对象定义的无参数构造函数?

如果我从“x => x.Values”更改为“x => x.Name”,那么还会出现错误“There is no ViewData item of type'IEnumerable'has key'DDLView.Name'。 “

编辑模板

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

控制器

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" /> 

}

回答

3

的问题是,的SelectList没有参数的构造函数和模型绑定不能实例化,但你试图将它张贴回来。

为了解决两件事情在你实现你的问题的变化:在编辑器中的模板

1)更改

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

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

2)旁添加到您的原始DropDownListViewModel

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

现在,您的发布操作参数将填充正确的值。

+0

thnx的回复,但wht应该写在视图和编辑器模板? – user584018 2012-07-12 00:25:06

相关问题