2013-04-08 76 views
1

更新:我为选择列表项目添加了“绑定排除”。没有为此对象定义的无参数构造函数。 MVC4 Razor,已经在构造函数中精选了任何参数

现在,我越来越没有IEnumerable类型的ViewDataItem有他们键等等等等......

如果我不能使用视图模型的选择列表,然后有什么意义?

在POST操作中获取此错误。我知道这已经被问过,但我没有按照说明无济于事。任何想法可能是错的?不知道我是否应该包括观点或不...

这里是模型:

公共类推广 {

[DisplayName("Number of Mailings")] 
    [Range(1, 100000,ErrorMessage="Please a positive number for Number of Mailings")] 
    public int mailings { get; set; } 
    [DisplayName("Number of Calls")] 
    public int pcalls { get; set; } 
    [DisplayName("Number of Emails")] 
    public int emails { get; set; } 
    [DisplayName("Number of Walkins")] 
    public int walkins { get; set; } 
    [DisplayName("Number of Faxes")] 
    public int faxes { get; set; } 
    public int osid { get; set; } 
    public int month { get; set; } 
    public int year { get; set; } 

    public Outreach() 
    { 
    } 
} 
} 

这里是视图模型:

public class OutreachViewModel 
    { 
    [DisplayName("Outreach Specialist")] 
    public SelectList OutreachSpecialist{ get; set; } 
    public SelectList Year { get; set; } 
    public SelectList Month { get; set; } 

    public Outreach Out {get; set;} 
} 

这里是控制器:

public ActionResult Create() 
     { 
      List<tblOutreachSpecialist> spec = repo.getAllSpecialists(); 
      List<pYear> years=repo.getAllYears(); 
      List<pMonth> months=repo.getAllMonths(); 

      OutreachViewModel vw = new OutreachViewModel(); 

      vw.Year = new SelectList(years, "id", "pYear1"); 
      vw.Month = new SelectList(months, "id", "pMonth1"); 
      vw.OutreachSpecialist = new SelectList(spec, "OSID", "LastName"); 

      return View(vw); 
     } 

     [HttpPost] 
     public ActionResult Create(OutreachViewModel vm) 
     { 
      if (ModelState.IsValid) 
      { 
       repo.Add(vm.Out); 
       repo.Save(); 

      } 
      return View(vm); 
     } 
+0

你在哪里得到错误? – AaronLS 2013-04-08 23:42:48

+0

在获取或邮政? – AaronLS 2013-04-08 23:44:23

+0

在帖子中获取它。 – rsteckly 2013-04-08 23:45:50

回答

1

考虑为post方法使用不同的视图模型。

  public class OutreachViewModelForCreate 
      { 
       public Outreach Out { get; set; } 
      } 

然后,让您的发帖采取更简单的视图模型。如果模型状态无效,你需要重新显示视图以获得新的用户输入,你可以调用一个方法来创建视图模型转换成显示视图模型的实例:

  [HttpPost] 
      public ActionResult Create(OutreachViewModelForCreate result) 
      { 
       if (ModelState.IsValid) 
       { 
        //write to repo 
       } 
       var displayVm = getCreateDisplayViewModel(); 

       displayVm.Out = result.Out; 

       return View(displayVm); 
      } 

你也可以使用自定义模型绑定器,但我个人更喜欢这种模式。

更新:我看你去绑定排除。我会在这里留下以防万一。

相关问题