Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
447 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...