Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

asp.net mvc - MVC Partial Model Updates

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...