I'm working on an ASP.NET MVC project. I have a form that is strongly typed. Is it considered good practice to add serialisation attributes to the same view model to control how the data is serialized once it is posted to the server. For example, I have many properties that are strictly used to show/hide UI components. Can I add [XmlIgnoreAttribute] to each of these properties in the view model so they won't be serialised or is it better to create a completely difficult class for serialization.
2Please do not cross-post: stackoverflow.com/q/34034501– user22815Dec 2, 2015 at 3:57
Conceptually, consider viewing and updating. They're very different things. Using a distinct ViewModel and UpdateModel is sensible. The ViewModel contains everything the view needs to do its job (that it doesn't already have). As such, it might contain select options, background colors, image paths... who knows? When you update the data from the ViewModel, it doesn't make much sense to pass those properties along.
As you mention, one option is to fuss with bindings so you don't get the unneeded data. That leaves me cold, however. I'd much rather see an action parameter that does exactly what it means. An explicit UpdateModel does the trick. Sometimes, you can simply recycle a domain model. If the data coming back from the UI is a little trickier (maybe it maps to more than one domain model), a separate UpdateModel serves you well.
Keep in mind, this isn't necessarily a common practice from what I see in the field. Using that same criteria, however, I'd note that brushing your teeth after meals also appears to be an uncommon practice and I'm not giving that up any time soon.
I'm relatively new to asp.net. Is there a better approach (more comman practice) to serializing form data that you know off? Dec 2, 2015 at 14:02
By default, if you name your HTML inputs properly (the MVC HtmlHelper does this for you), MVC will bind form values to corresponding properties/names in an action's parameters. That means things work the same if you choose a ViewModel or UpdateModel. In general, you shouldn't have to fuss with [XmlIgnore] or the like. You can Exclude properties, but that causes other issues... Dec 2, 2015 at 14:54
Maybe search a bit for MVC model binding tips and tutorials: from the beginning. Get a better sense of how model binding works under the hood. It's related to serialization, but that's not really the important concept. The topic's a little too big for a forum like this. Dec 2, 2015 at 14:57
Ok, Thanks for the help. I'll take your advice and use a separate class to serialize the view model object posted to the server. Dec 2, 2015 at 21:31