Controller parameter does not become null

asp.net-mvc, c#, controller

Solution

The MVC model binder has taken over. What I originally posted would work in instances that do not go through the model binder. However, based on other answers on SO and my own quick testing, it appears that a viewmodel parameter will never be null due to how the binder works and ties properties to form values.

In your instance, I would check if both latitude and longitude are null to see if nothing was passsed. Which means you will need to make them nullable on your ViewModel

public class Location : ILocation
    {
       public DbGeography Coordinates { get; set; }

       public double? Latitude { get; set; }

       public double? Longitude { get; set; }
    }

Updated Controller Code

if (location.Latitude == null && location.Longitude == null)
    {
        // init location or smth
    }

Problem

I ran into the following problem: I've got a asp.net mvc 5 controller with a reference type as a parameter: ``` [Route("")] [HttpGet] public ActionResult GetFeeds(Location location) { if (location == null) { // init location or smth } // Do smth with location return new EmptyResult(); } ``` You will notice that I'm using AttributeRouting. There are NO other methods with the name of this action. However - this is my location class: ``` public class Location : ILocation { public DbGeography Coordinates { get; set; } public double Latitude { get; set; } public double Longitude { get; set; } } ``` Nothing special here (the interface defines all of those properties). If I'm accessing the controllers action (actually using powershell) and passing something like: ``` http://localhost:2000/Feed?latitude=23.1&longitude=37 ``` everthing works fine but if I'm using ``` http://localhost:2000/Feed ``` the location parameter is NOT null (it is a new Location with default values), which is the behavior I want to have :( . Does anyone have an idea why this happens? Thanks in advance

Original source

Related problems