Last post Jan 03, 2018 07:53 AM by Fouad Roumieh
Dec 21, 2017 07:21 PM|Fouad Roumieh|LINK
I would like to hide some of my viewmodel properties based on the Verb used, because I don't want to create different viewmodels for each action.
For example if its for post, I would like like to allow them to Ignore the Id, but for put the Id can exist.
I'm using the FromBody attribute to bind my parameters.
So is it possible to make the property nullable for specific action?
Dec 21, 2017 07:34 PM|mgebhard|LINK
The Bind attribute can help stop an over-posting situation due to model binding.
Dec 21, 2017 09:11 PM|Fouad Roumieh|LINK
Thanks for the post.
The Bind attribute doesn't seem a flexi one.
Do you have an Idea how AutoMapper can help, as mentioned here by Hanelmann:
Or, the correct answer. Don't
let models that look like this get anywhere near the user. This
is the case for ViewModels. Make a model that looks like the View. Then do the work. You can make the work
easier with something like AutoMapper.
Dec 21, 2017 09:15 PM|mgebhard|LINK
Automapper is API that maps one object to another. You can learn more by reading the AutoMapper documentation.
Dec 21, 2017 09:44 PM|Fouad Roumieh|LINK
I know it but how does it help in solving the problem am talking about?
Dec 22, 2017 03:52 PM|bruce (sqlwork.com)|LINK
the suggestion is that you make a view model for every action, and use auto mapper to copy from the BI model to the view modal, which is the best practice.
Jan 03, 2018 07:53 AM|Fouad Roumieh|LINK
I followed the example from the internet to Un-ignore the specific properties that I want to show in the response body only:
public class SerializerContractResolver : DefaultContractResolver
private readonly Dictionary<Type, HashSet<string>> _shows;
_ignores = new Dictionary<Type, HashSet<string>>();
_renames = new Dictionary<Type, Dictionary<string, string>>();
_shows = new Dictionary<Type, HashSet<string>>();
public void ShowProperty(Type type, params string jsonPropertyNames)
_shows[type] = new HashSet<string>();
foreach (var prop in jsonPropertyNames)
} protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
var property = base.CreateProperty(member, memberSerialization);
if (IsShow(property.DeclaringType, property.PropertyName))
property.Ignored = false;
And then in the controller action I call it:
var serializer = new SerializerContractResolver();
return Ok(JsonConvert.SerializeObject(eventDto, new JsonSerializerSettings
ContractResolver = serializer,
Formatting = Formatting.Indented