在ASP.NET MVC中重载了ViewModel构造函数和HttpPost

时间:2015-03-06 03:04:11

标签: asp.net-mvc asp.net-mvc-4 razor asp.net-mvc-5

我在StackOverflow中找到的最接近的问题是我所拥有的 Posting data when my view model has a constructor does not work

模型

    public class Customer
    {
        public int Id { get; set; }                
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

视图模型

    public class CustomerViewModel
    {
        public Customer Customer { get; set; }

        public CustomerViewModel(Customer customer)
        {
            Customer = customer;        
        }
    }

控制器代码

    public ActionResult CreateCustomer()
    {
        Customer c = new Customer();
        CustomerViewModel cvm = new CustomerViewModel(c);
        return View(cvm);
    }

    [HttpPost]
    public ActionResult CreateCustomer(CustomerViewModel customer)
    {
       // do something here
    }

查看代码

    @model Blah.Models.CustomerViewModel

    @{
        ViewBag.Title = "CreateCustomer";
     }

    <h2>CreateCustomer</h2>

    @using (Html.BeginForm()) 
    { 
        <div class="editor-label">
          @Html.LabelFor(model => model.Customer.FirstName)
        </div>
        <div class="editor-field">
          @Html.EditorFor(model => model.Customer.FirstName)
          @Html.ValidationMessageFor(model => model.Customer.FirstName)
        </div>

        <div class="editor-label">
          @Html.LabelFor(model => model.Customer.LastName)
        </div>
        <div class="editor-field">
          @Html.EditorFor(model => model.Customer.LastName)
          @Html.ValidationMessageFor(model => model.Customer.LastName)
        </div>

        <p>
          <input type="submit" value="Create" />
        </p>
    }

错误

enter image description here

解决错误但没有帮助的解决方案

  • 添加默认构造函数(参数为空 - 不符合我的目的)
  • 没有重载的构造函数(我的模型将为空)

问题

我想我需要一个自定义模型绑定器。不知道如何创建一个: - (

(或)

我想知道我在这里有哪些其他选择

1 个答案:

答案 0 :(得分:2)

您需要添加无参数构造函数。

public class CustomerViewModel
{
    public Customer Customer { get; set; }

    public CustomerViewModel()
    {
    }
    public CustomerViewModel(Customer customer)
    {
        Customer = customer;        
    }
}

您认为这是“不工作”的原因&#39;是另一个问题。您的模型有一个名为Customer的属性,它是一个复杂类型,POST方法的参数也被命名为customerDefaultModelBinder不区分大小写)。结果,绑定失败。您需要将参数名称更改为除某个属性的名称之外的任何名称,例如

[HttpPost]
public ActionResult CreateCustomer(CustomerViewModel model)