提交一个模型来操作它是从视图模型的类型不同 [英] Submitting a model to action that is different from view model's type

查看:182
本文介绍了提交一个模型来操作它是从视图模型的类型不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个型号:

 公共类PersonViewModel
{
    公众诠释编号{获得;组; }
    公共字符串名称{;组; }
    公共字符串名称{获取;组; }
}

公共类DetailViewModel
{
     公开的IEnumerable<字符串>标题{获得;组; }
     公共PersonViewModel人{获得;组; }
}
 

的形式是psented有两个字段,第一个字段作为名称,第二场是对标题的下拉$ P $ (先生,小姐太太,等。)

视图此页面是强类型为 DetailViewModel ,并在控制器中的保存方法接受一个参数类型 PersonViewModel

由于视图是强类型的一种类型,它的不同的的从表单操作的参数类型,在名称中的Htt prequest不匹配什么MVC期待的动作。

时有可能有MVC绑定正确的模式不匹配的不必手动指定表单字段名称? (如:我还是想用 @ Html.TextBoxFor(M => m.Person.Name)

有关澄清,正在提交表单字段名称类似于以下内容:

  

Person.Name =马修和放大器; Person.Title =先生

在我需要如下(为模型绑定工作):

  

名称=马修和放大器;标题=先生

解决方案

您可以使用的 preFIX 属性 BindAttribute 的操作方法

 公众的ActionResult编辑([绑定(preFIX =人)PersonViewModel模型)
{
}
 

这基本上是剥离 $ P $的属性名PFIX同时结合

I have two models:

public class PersonViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Title { get; set; }
}

public class DetailViewModel
{
     public IEnumerable<string> Titles { get; set; }
     public PersonViewModel Person { get; set; }         
}

The form is presented with two fields, the first field being the Name, the second field being the a dropdown of Titles (Mr., Mrs. Miss., etc.)

The view for this page is strongly typed to DetailViewModel, and the Save method in the controller accepts a parameter of type PersonViewModel.

Since the view is strongly typed to a type that is different from the form action's parameter type, the names in the HttpRequest do not match what MVC is expecting in the action.

Is it possible to have MVC bind correctly with the model mismatch without having to manually specify form field names? (eg. I still want to use @Html.TextBoxFor(m => m.Person.Name))

For clarification, the form field names that are being submitted are similar to the following:

Person.Name=Matthew&Person.Title=Mr.

Where I need the following (for model binding to work):

Name=Matthew&Title=Mr.

解决方案

You can use the Prefix property of BindAttribute in the action method

public ActionResult Edit([Bind(Prefix="Person")]PersonViewModel model)
{
}

This essentially strips the Person prefix from the property name while binding

这篇关于提交一个模型来操作它是从视图模型的类型不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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