Overloaded ViewModel Constructor and HttpPost in A

2019-09-01 06:35发布

The closest question I found in StackOverflow to what I have is Posting data when my view model has a constructor does not work

Model

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

ViewModel

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

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

Controller Code

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

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

View Code

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

Error

enter image description here

Solutions that just get rid of the error but not helpful

  • Adding a Default Constructor (parameter is empty - doesn't serve my purpose)
  • Dont have the overloaded constructor (My Model will be empty then)

Question

I guess I need a custom model binder here. Don't know how to create one :-(

(or)

I would like to know what other options I have here

1条回答
叛逆
2楼-- · 2019-09-01 07:11

You need to add a parameterless constructor.

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

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

The reason you think this is 'not working' is another issue. Your model has a property named Customer which is a complex type and the parameter of your POST method is also named customer (the DefaultModelBinder is not case sensitive). As a result, binding fails. You need to change the parameter name to anything other than the name of one of your properties, for example

[HttpPost]
public ActionResult CreateCustomer(CustomerViewModel model)
查看更多
登录 后发表回答