简体   繁体   中英

Binding properties of an object in a ViewModel

Let's say I have this Model:

public class Person
{
    public string forename { get; set; }
    public string surname { get; set; }
    public string randomValue { get; set; }
}

and this ViewModel:

public class PersonViewModel
{
    public Person person { get; set; }
    public bool viewSpecificOption { get; set;}
}

Then this controller:

public ActionResult Create([Bind(Include = "person, viewSpecificOption")] PersonViewModel viewModel)
{
    //some code here...
}

You can see I bind the 'Person', but what if I dont want to include the 'Person.randomValue'

I know I could replace the 'Person' in the viewModel with a string for forename and surname but then I'd have to manually convert it to a actual Person.

Any suggestions on how I can achieve this is a neat and secure way?

Thanks to the article @StephenMuecke linked in their comment. I'm satisfied with taking the approach of not using bind and just using specific ViewModels.

But if anyone comes accross this question and has a better way that avoids having to then map the ViewModel to the actual Model, please tell me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM