Search code examples
asp.net-coreasp.net-core-mvcasp.net-core-2.0asp.net-core-mvc-2.0

How to handle a unit conversion property in ASP.Net Core MVC model?


Let's say you have a model property like this:

[Display(Name = "Length (ft)"]
public double LengthFt {get; set;}

Now you want another property that has length in meters that will be used in your input and output forms:

[Display(Name = "Length (m)"]
[NotMapped]
public double LengthMeters
{
    get => LengthFt * 0.3048;
    set => LengthFt = value / 0.2048;
}

Should this work? Mine (a much more complex example than this) is working on the "get" portion (returning LengthMeters correctly when LengthFt is set), and is working on the Create form (the standard Create view from ASP.Net Core MVC), but is not working on the Edit. The Edit form shows the correct initial value, but when I overwrite it and click "Save", both fields are now 0. It's like the Edit isn't seeing the change to the NotMapped element, but the Create action does.

Is there a more elegant way to handle these types of transformations?


Solution

  • The "LengthMeters" was omitted from the Bind command on the Edit method in the controller. When properly bound, this technique seems to work fine.

    Still wondering if there is a more elegant way of doing this, but it seems to be working now.