MVC Partial Model Updates

2020-02-02 03:22发布

问题:

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).

I know of two methods:

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.

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) 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?

回答1:

Use the System.ComponentModel.DataAnnotations.MetadataType.

Something like:

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