MVC自定义视图模型和经销商的结合 [英] MVC Custom ViewModel and auto binding

查看:111
本文介绍了MVC自定义视图模型和经销商的结合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义视图模型定义如下:

I have a custom ViewModel defined as :

public class SampleFormViewModel
{
    public SampleFormViewModel(SelectList companies, Widget widget)
    {
        Companies = companies;
        Widget = widget;
    }

    public SelectList Companies { get; private set; }
    public Widget Widget { get; private set; }
}

在我编辑POST处理程序,我有以下条目:

In my Edit POST handler I have the following entry:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(SampleFormViewModel model)
{

编辑格式设置为:

Edit form is set up as:

Inherits="System.Web.Mvc.ViewPage<Sample.Web.Models.SampleFormViewModel>"

和它只是吹了起来,不知道这是怎么回事,有以下错误:
此对象定义无参数的构造函数。
某些我在这里失去了一些东西真的很明显。有些背景下,GET完美的作品并显示选择列表下拉预期。
我猜的自动绑定回自定义视图模式是什么是失败的,但不知道该怎么办才好。

And it just blows up, not sure what’s going on, has the following error: No parameterless constructor defined for this object. Certain I’m missing something really obvious here. Some background, the GET works perfectly and display the dropdown from the SelectList as expected. I’m guessing the auto-binding back to the custom view model is what is failing but not sure what to do about it.

推荐答案

您需要有一个参数的构造函数,我相信性能需要有公共setter方法​​。默认粘结剂使用构造不带参数创建对象,然后使用反思的公共属性,从表单/查询参数的值。

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

我怀疑,虽然,你真正想要做的是没有得到视图模型,但潜在的Widget模式和形式后选择列表值。我不认为粘结剂将能够重建对职位的的SelectList,因为它只有在参数选择的值。

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 )
{
}

这篇关于MVC自定义视图模型和经销商的结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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