MVC Custom ViewModel and auto binding

前端 未结 2 1100
Happy的楠姐
Happy的楠姐 2021-02-06 06:48

I have a custom ViewModel defined as :

public class SampleFormViewModel
{
    public SampleFormViewModel(SelectList companies, Widget widget)
    {
        Compa         


        
2条回答
  •  逝去的感伤
    2021-02-06 07:04

    You need to have a parameterless constructor and I believe that the properties need to have public setters. The default binder creates the object using a constructor that takes no parameters, then uses reflection on the public properties to set values from the form/query parameters.

    public class SampleFormViewModel
    {
        public SampleFormViewModel() { }
    
        public SelectList Companies { get; set; }
        public Widget Widget { get; set; }
    }
    

    I suspect, though, that what you really want to do is not get the view model, but the underlying Widget model and select list value on form post. I don't think the binder will be able to reconstruct a SelectList on post since it only has the selected value in the parameters.

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit( int CompanyID, Widget widget )
    {
    }
    

提交回复
热议问题