user1751825 user1751825 - 24 days ago 5 Question

MVC 5 - Don't serialize property if default value

I have a viewmodel, which I use to create a business search filter object. In my view, I create an actionlink like so...

@Html.ActionLink("Search Link",
routeValues:=New MyFilterViewModel() With {.Field1 = "Some Value", .Field2 = "Some other value"}, htmlAttributes:=Nothing)

This works fine. It serializes the viewmodel properties as querystring parameters, which are then bound by the controller action.

The filter view model has a lot of other properties though, most of which aren't relevant, but they're all still serialized in the URL parameters, even though most aren't set.

Is there a way to decorate the modelview properties, so they will only be serialized if they're assigned (not default value)?


You could use the DefaultHandling enum in [JsonProperty] attribute. Decorate your properties likeso.

[JsonProperty("MyProp", DefaultValueHandling = DefaultValueHandling.Ignore)]  
public string MyProp { get; set; }