0

我是 MVC3 的新手,经过 2 天的阅读,我找不到我做错了什么。这是场景:

我有一个强类型视图:

<%@ Page Title="" Language="C#" 
MasterPageFile="~/Views/Shared/NestedMasterPage.Master"    
Inherits="System.Web.Mvc.ViewPage<AdminToolMVC.Models.PageModels.MembershipVM>" %>

<% using (Html.BeginForm("UpdateUser", "Admin")) 
{ %>
   <%: Html.CheckBoxFor(m => m.Tab6VM.Programs[0].Selected, 
      new { id = "prog1" })%>
   <%: Model.Tab6VM.Programs[0].Description %></br>
   <%: Html.CheckBoxFor(m => m.Tab6VM.Programs[1].Selected, 
      new { id = "prog2" })%>
   <%: Model.Tab6VM.Programs[1].Description %></br>
   <%: Html.CheckBoxFor(m => m.Tab6VM.Programs[2].Selected, 
     new { id = "prog3" })%>
   <%: Model.Tab6VM.Programs[2].Description %></br>
   <%: Html.CheckBoxFor(m => m.Tab6VM.Programs[3].Selected, 
     new { id = "prog4" })%>
   <%: Model.Tab6VM.Programs[3].Description %></br>
   <input type="submit" id="btnUpdate"  value="Update"  />
<%} %>

在我的管理控制器中:

public ActionResult Index()
{
     //return some view
}

[HttpPost]
    public ActionResult UpdateUser(MembershipVM pageModel)  
    {
        UserAdminDW dataWriter;
        Models.PageModels.MembershipVM = 
          new  Models.PageModels.MembershipViewModel();
        try
        {
            model = StateHelper.MEMBERSHIP;
        }
        catch (Exception e)
        {

            return RedirectToAction("SessionExpired", "Error");
        }
    }

我的印象是,我的强类型视图页面应该将用户在表单中更改的数据发送到我的 AdminController 类中的 UpdateUser 方法。

但相反,我得到的是“没有为此对象定义的无参数构造函数”。错误。

我试图从视图中向控制器调用添加一个参数,但是通过控制器的页面模型为空。我要做的就是在页面上显示用户数据后,让用户更新一些信息并将其发送回控制器,这样我就可以将其保存在数据库中。我错过了什么?我没有使用 Razor 引擎,只使用经典的 MVC3。谢谢您的帮助。

4

1 回答 1

2

当模型绑定器尝试填充对象(视图模型)并且找不到公共/无参数构造函数(哦,rly?)时,会发生错误。

例子

视图模型

public class CustomerViewModel {
    public CustomerViewModel() { // <- public constructor without params.
        Created = DateTime.Now;
    }

    public Guid CustomerId { get; set; }
    public DateTime Created { get; set; }
    public AddressViewModel Address { get; set; }
}

public class AddressViewModel {
    public AddressViewModel(Guid customerId) { // <- BOOM! AddressViewModel have none parameterless constructor, so it can't be created
        CustomerId = customerId;
    }        

    public Guid CustomerId { get; set; }
    public string Street { get; set; }
    public string ZipCode { get; set; }
    public string Country { get; set; }

    public CustomerViewModel Customer { get; set; }
}

行动

[HttpPost]
public ActionResult UpdateCustomer(CustomerViewModel customer) {
    // when modelbinder are trying to create the 'customer', it sees that CustomerViewModel have an AddressViewModel(which have none parameterless constructor) property, and you know what happen.
}

希望能帮助到你。

于 2012-10-13T00:08:36.347 回答