【问题标题】:MVC custom viewmodel problemsMVC 自定义视图模型问题
【发布时间】:2009-05-19 04:09:27
【问题描述】:

我是一个 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 中获取完整的输出并相应地对其进行解析。麻烦的是,这抱怨没有用于视图模型的无参数构造函数(并且没有) - 我不确定解决这个问题的正确方法。我尝试过的任何方法都不起作用,我真的需要一些帮助!

如果有帮助,我的视图如下所示:

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

【问题讨论】:

    标签: c# asp.net-mvc viewmodel


    【解决方案1】:

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

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

    【讨论】:

    • 一直在做一些研究并得出结论——正如你所说——自定义模型绑定器正是我所需要的。现在我只需要弄清楚如何写一个!感谢您的评论 - 我会采纳您的建议,看看是否可以实现。
    【解决方案2】:

    我相信我明白了:

    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”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-15
      • 2011-01-22
      • 1970-01-01
      相关资源
      最近更新 更多