MVC自定义viewmodel问题

时间:2009-05-19 04:09:28

标签: c# asp.net-mvc viewmodel

我是一个MVC新手,所以你必须原谅我想象的一个基本问题。

我创建了一个自定义视图模型,以便在我的表单中有一个多选列表:

public class CustomerFormViewModel
{
    public Customer Customer { get; private set; }
    public MultiSelectList CustomerType { get; private set; }

    public CustomerFormViewModel(Customer customer)
    {
        Customer = customer
        // this returns a MultiSelectList:
        CustomerType = CustomerOptions.Get_CustomerTypes(null);
    }
}

我发现我的第一次尝试只捕获了多选的第一个值,我猜这是因为我的创建动作看起来像这样:

    // GET: /Buyer/Create
    public ActionResult Create() { ... }

    // POST: /Buyer/Create
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(Customer customer) { ... }

所以,我决定将其更改为:

    // GET: /Buyer/Create
    public ActionResult Create() { ... }

    // POST: /Buyer/Create
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(CustomerFormViewModel model) { ... }

这样我就可以从MultiSelectList获取完整输出并相应地解析它。麻烦的是,这抱怨说viewmodel没有无参数构造函数(并且没有) - 而且我不确定正确的方法来解决这个问题。我尝试过的任何东西都没有用,我真的需要一些帮助!

如果有帮助,我的观点如下:

<%@  Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MySite.Controllers.CustomerFormViewModel>" %>
...
<% using (Html.BeginForm())
    <%= Html.ListBox("CustomerType", Model.CustomerType)%>
...

2 个答案:

答案 0 :(得分:1)

您是否尝试过自定义ModelBinder?我不确定我是否清楚地理解你的代码,但这可能是你的起点:

public class CustomerFormViewModelBinder : DefaultModelBinder
{
    protected virtual object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
    {
        var model = new CustomerFormViewModel(customer)
    }
}

答案 1 :(得分:1)

我相信我明白了:

public class CustomerModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var form = controllerContext.HttpContext.Request.Form;

        Customer customer = base.BindModel(controllerContext, bindingContext) as Customer;

        if (customer!= null)
        {
            customer.CustomerType= form["CustomerType"];
        }

        return customer;
    }
}

与global.asax文件的Application_Start()中的条目一起:

        ModelBinders.Binders.Add(typeof(Customer), new CustomerModelBinder());

将逗号分隔的列表框选择列表放在字段中。例如“1,3,4”。