MVC部分模型更新 [英] MVC Partial Model Updates

查看:67
本文介绍了MVC部分模型更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常发现自己只想展示和编辑模型中的某些字段.假设我有一个代表地址的模型,也许我只想让表单更新城市和邮政编码字段(不好的例子,但希望它能解释这种情况).

I often find myself in the situation where I only want to present and edit some fields from my model. Let's say I have a model that represts an address, perhaps I just want the form to update the city and post code fields (bad example, but hopefully it explains the scenario).

我知道两种方法:

1)将不需要的字段保留在表单上的隐藏输入元素中,或者... 2)创建一个仅定义我需要的字段的专用视图模型.

1) Persist the unwanted fields in hidden input elements on the form, or... 2) Create a dedicated view model that just defines the fields I need.

我赞成选择#2,但是我没有一种很好的干净方法将视图模型中的数据合并到控制器动作中的真实"模型中.此刻,我遵循这种方法...

I favour option #2, but I don't have a nice clean way of merging the data from the view model back into the 'real' model within the controller action. At the moment, I follow this approach...

1)将我要保存的记录存储在视图模型的隐藏字段中 2)页面发回时,控制器检索原始记录,我手动将视图模型中的每个字段分配给实际模型 3)将实际模型保存回数据存储.

1) Store the record I'd in a hidden field on the view model 2) When the page posts back, the controller retrieves the original record and I manually assign each field from the view model to the real model 3) Save the real model back to the data store.

这可行,但是这是很多工作,并且很容易错过分配/重新分配的任务,我想知道是否有人知道另一种方法?

This works, but it is quite a lot of work and very easy to miss an assignment/reassignment and I was wondering if anyone knew of another approach?

推荐答案

使用 System.ComponentModel.DataAnnotations.MetadataType .

类似的东西:

public class BaseClassOfProperties
{
   public string Name { get; set; }
}

public interface INameViewableProperties
{
   [Display(name = "Your Name")]
   string Name { get; set; }
}

public interface INameHiddenProperties
{
   //[scaffoldColumn(false)] this completely hides the fields
   [UIHint("Hidden")] // i think...
   string Name { get; set; }
}

[MetadataType(typeof(INameViewableProperties)]
public class NameViewAbleProperties : BaseClassOfProperties
{
}

[MetadataType(typeof(INameHiddenProperties)]
public class NameHiddenProperties : BaseClassOfProperties
{
}

这篇关于MVC部分模型更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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