模型包含多个对象视图模型绑定 [英] Model binding for a ViewModel containing multiple objects

查看:154
本文介绍了模型包含多个对象视图模型绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有型ProductListingViewModel又包含一个ProductViewModel的强类型视图。 (包括自定义视图模型)。

I have a strongly typed view of type ProductListingViewModel which in turn contains a ProductViewModel. (both custom view models).

我有我的网页上某种形式的元素,这些都是像这样创建:

I have some form elements on my page and these are created like so:

<%: Html.DropDownListFor(m => m.ProductViewModel.CategoryId, Model.Categories)%>

在产生HTML:

which generates the HTML:

<select name="ProductViewModel.CategoryId" id="CategoryId">

使用默认的模型绑定我的预期,当我张贴到我控制器操作,它接受类型ProductListingViewModel的参数,它会知道的有关数据来填充ProductViewModel.CategoryId。

With the default model binding I expected that when I post to my controller action which accepts a parameter of type ProductListingViewModel, that it'd know to populate the ProductViewModel.CategoryId with the relevant data.

选择列表的名称似乎表明,它知道有一个的CategoryId属性ProductViewModel但是当我张贴到我控制器的方法,该ProductViewModel为空。如果我建ProductListingViewModel期间创建这个那么它不再为空,但默认联似乎并不如我想像的要填充的属性。

The name of the select list seems to indicate that it knows there's a ProductViewModel with a CategoryId property however when I post to my controller method, the ProductViewModel is null. If I create this during construction of the ProductListingViewModel then it's no longer null but the default binder doesn't seem to be populating the properties as I expected.

这是一个自定义模型粘结剂的情况下,还是我只是失去了一些东西根本?

Is this a case for a custom model binder or am I just missing something fundamental?

干杯。

推荐答案

让我试着总结(纠正我,如果我错了)。

Let me try to summarize (correct me if I am wrong).

型号:

public class ProductListingViewModel
{
    public ProductViewModel ProductViewModel { get; set; }
    public IEnumerable<SelectListItem> Categories { get; set; }
}

public class ProductViewModel
{
    public string CategoryId { get; set; }
}

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new ProductListingViewModel
        {
            Categories = new SelectList(new[]
            {
                new { Value = "1", Text = "category 1" },
                new { Value = "2", Text = "category 2" }
            }, "Value", "Text")
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(ProductListingViewModel model)
    {
        return View(model);
    }
}

查看:

<% using (Html.BeginForm()) { %>
    <%: Html.DropDownListFor(m => m.ProductViewModel.CategoryId, Model.Categories)%>
    <input type="submit" value="OK" />
<% } %>

现在,当您提交表单,您将得到:

Now when you submit the form you will get:

model.ProductViewModel.CategoryId = the id that was selected in the drop down list

是不是你所追求的?

Isn't what you are after?

这篇关于模型包含多个对象视图模型绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆