UnitsNet - How to use it in MVC?












0















How to use the UnitsNet nuget package in an MVC web application ?



For example I have my object:



public class UnitsNetTestViewModel
{
public int AnInput { get; set; }
public UnitsNet.Temperature OutdoorTemperature { get; set; }
}


Then my view



@model WebApplication.Models.UnitsNetTestViewModel
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

@Html.LabelFor(model => model.AnInput)
@Html.EditorFor(model => model.AnInput)
<br/>

@Html.LabelFor(model => model.OutdoorTemperature)
@Html.EditorFor(model => model.OutdoorTemperature)
<button type="submit">Submit</button>
}


In my controller



    public class UnitsNetTestController : Controller
{
// GET: UnitNetsTest
public ActionResult Index()
{
var model = new Models.UnitsNetTestViewModel {OutdoorTemperature = Temperature.FromDegreesFahrenheit(80)};
return View("~/Views/UnitsNetTest.cshtml", model);
}

[HttpPost]
public ActionResult Index(Models.UnitsNetTestViewModel model)
{
if (ModelState.IsValid)
{
return View("~/Views/Home/Index.cshtml");
}
return View("~/Views/UnitsNetTest.cshtml", model);
}
}


I have tried using EditorFor or TextBoxFor.
I have also tried binding on a different part of the object:



model => model.OutdoorTemperature.Value
model => model.OutdoorTemperature.DegreesFahrenheit
model => model.OutdoorTemperature


Even when using the EditorFor model.OutdoorTemperature combination, I get the full object input fields, when I update a value, it always return as zero in the controller submit.



What Am I doing wrong ?



Thanks.



EDIT 1



Trying to understand how the UnitsNet property is working, I added a subclass to my model to see if my subclass value will be available back in the controller (even if I already know that it will work). What I have notice from that : in the watch, the Value of my model.Other property is {...WebApplication.Models.SubClass} and the type is also ...WebApplication.Models.SubClass. But for model.OutdoorTemperature, the Value is {0 K} and the Type is UnitsNet.Temperature.
Could it be a clue ?



Here is a print screen:
Debugging Watch Printscreen



Updated class:



public class UnitsNetTestViewModel
{
public int AnInput { get; set; }
public UnitsNet.Temperature OutdoorTemperature { get; set; }
public SubClass Other { get; set; }
}

public class SubClass
{
public int Value { get; set; }
public int MySubClassValue { get; set; }
}


Updated View:



@model WebApplication.Models.UnitsNetTestViewModel
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

@Html.LabelFor(model => model.AnInput)
@Html.EditorFor(model => model.AnInput)
<br />

@Html.LabelFor(model => model.OutdoorTemperature)
@Html.TextBoxFor(model => model.OutdoorTemperature.Value)

<br />
@Html.LabelFor(model => model.Other)
@Html.TextBoxFor(model => model.Other.Value)

<br />
@Html.LabelFor(model => model.Other)
@Html.TextBoxFor(model => model.Other.MySubClassValue)


<button type="submit">Submit</button>
}


EDIT 2



The UnitsNet.Temperature is a struct, not a class. Will probably need a custom model binder.










share|improve this question





























    0















    How to use the UnitsNet nuget package in an MVC web application ?



    For example I have my object:



    public class UnitsNetTestViewModel
    {
    public int AnInput { get; set; }
    public UnitsNet.Temperature OutdoorTemperature { get; set; }
    }


    Then my view



    @model WebApplication.Models.UnitsNetTestViewModel
    @using (Html.BeginForm())
    {
    @Html.AntiForgeryToken()

    @Html.LabelFor(model => model.AnInput)
    @Html.EditorFor(model => model.AnInput)
    <br/>

    @Html.LabelFor(model => model.OutdoorTemperature)
    @Html.EditorFor(model => model.OutdoorTemperature)
    <button type="submit">Submit</button>
    }


    In my controller



        public class UnitsNetTestController : Controller
    {
    // GET: UnitNetsTest
    public ActionResult Index()
    {
    var model = new Models.UnitsNetTestViewModel {OutdoorTemperature = Temperature.FromDegreesFahrenheit(80)};
    return View("~/Views/UnitsNetTest.cshtml", model);
    }

    [HttpPost]
    public ActionResult Index(Models.UnitsNetTestViewModel model)
    {
    if (ModelState.IsValid)
    {
    return View("~/Views/Home/Index.cshtml");
    }
    return View("~/Views/UnitsNetTest.cshtml", model);
    }
    }


    I have tried using EditorFor or TextBoxFor.
    I have also tried binding on a different part of the object:



    model => model.OutdoorTemperature.Value
    model => model.OutdoorTemperature.DegreesFahrenheit
    model => model.OutdoorTemperature


    Even when using the EditorFor model.OutdoorTemperature combination, I get the full object input fields, when I update a value, it always return as zero in the controller submit.



    What Am I doing wrong ?



    Thanks.



    EDIT 1



    Trying to understand how the UnitsNet property is working, I added a subclass to my model to see if my subclass value will be available back in the controller (even if I already know that it will work). What I have notice from that : in the watch, the Value of my model.Other property is {...WebApplication.Models.SubClass} and the type is also ...WebApplication.Models.SubClass. But for model.OutdoorTemperature, the Value is {0 K} and the Type is UnitsNet.Temperature.
    Could it be a clue ?



    Here is a print screen:
    Debugging Watch Printscreen



    Updated class:



    public class UnitsNetTestViewModel
    {
    public int AnInput { get; set; }
    public UnitsNet.Temperature OutdoorTemperature { get; set; }
    public SubClass Other { get; set; }
    }

    public class SubClass
    {
    public int Value { get; set; }
    public int MySubClassValue { get; set; }
    }


    Updated View:



    @model WebApplication.Models.UnitsNetTestViewModel
    @using (Html.BeginForm())
    {
    @Html.AntiForgeryToken()

    @Html.LabelFor(model => model.AnInput)
    @Html.EditorFor(model => model.AnInput)
    <br />

    @Html.LabelFor(model => model.OutdoorTemperature)
    @Html.TextBoxFor(model => model.OutdoorTemperature.Value)

    <br />
    @Html.LabelFor(model => model.Other)
    @Html.TextBoxFor(model => model.Other.Value)

    <br />
    @Html.LabelFor(model => model.Other)
    @Html.TextBoxFor(model => model.Other.MySubClassValue)


    <button type="submit">Submit</button>
    }


    EDIT 2



    The UnitsNet.Temperature is a struct, not a class. Will probably need a custom model binder.










    share|improve this question



























      0












      0








      0








      How to use the UnitsNet nuget package in an MVC web application ?



      For example I have my object:



      public class UnitsNetTestViewModel
      {
      public int AnInput { get; set; }
      public UnitsNet.Temperature OutdoorTemperature { get; set; }
      }


      Then my view



      @model WebApplication.Models.UnitsNetTestViewModel
      @using (Html.BeginForm())
      {
      @Html.AntiForgeryToken()

      @Html.LabelFor(model => model.AnInput)
      @Html.EditorFor(model => model.AnInput)
      <br/>

      @Html.LabelFor(model => model.OutdoorTemperature)
      @Html.EditorFor(model => model.OutdoorTemperature)
      <button type="submit">Submit</button>
      }


      In my controller



          public class UnitsNetTestController : Controller
      {
      // GET: UnitNetsTest
      public ActionResult Index()
      {
      var model = new Models.UnitsNetTestViewModel {OutdoorTemperature = Temperature.FromDegreesFahrenheit(80)};
      return View("~/Views/UnitsNetTest.cshtml", model);
      }

      [HttpPost]
      public ActionResult Index(Models.UnitsNetTestViewModel model)
      {
      if (ModelState.IsValid)
      {
      return View("~/Views/Home/Index.cshtml");
      }
      return View("~/Views/UnitsNetTest.cshtml", model);
      }
      }


      I have tried using EditorFor or TextBoxFor.
      I have also tried binding on a different part of the object:



      model => model.OutdoorTemperature.Value
      model => model.OutdoorTemperature.DegreesFahrenheit
      model => model.OutdoorTemperature


      Even when using the EditorFor model.OutdoorTemperature combination, I get the full object input fields, when I update a value, it always return as zero in the controller submit.



      What Am I doing wrong ?



      Thanks.



      EDIT 1



      Trying to understand how the UnitsNet property is working, I added a subclass to my model to see if my subclass value will be available back in the controller (even if I already know that it will work). What I have notice from that : in the watch, the Value of my model.Other property is {...WebApplication.Models.SubClass} and the type is also ...WebApplication.Models.SubClass. But for model.OutdoorTemperature, the Value is {0 K} and the Type is UnitsNet.Temperature.
      Could it be a clue ?



      Here is a print screen:
      Debugging Watch Printscreen



      Updated class:



      public class UnitsNetTestViewModel
      {
      public int AnInput { get; set; }
      public UnitsNet.Temperature OutdoorTemperature { get; set; }
      public SubClass Other { get; set; }
      }

      public class SubClass
      {
      public int Value { get; set; }
      public int MySubClassValue { get; set; }
      }


      Updated View:



      @model WebApplication.Models.UnitsNetTestViewModel
      @using (Html.BeginForm())
      {
      @Html.AntiForgeryToken()

      @Html.LabelFor(model => model.AnInput)
      @Html.EditorFor(model => model.AnInput)
      <br />

      @Html.LabelFor(model => model.OutdoorTemperature)
      @Html.TextBoxFor(model => model.OutdoorTemperature.Value)

      <br />
      @Html.LabelFor(model => model.Other)
      @Html.TextBoxFor(model => model.Other.Value)

      <br />
      @Html.LabelFor(model => model.Other)
      @Html.TextBoxFor(model => model.Other.MySubClassValue)


      <button type="submit">Submit</button>
      }


      EDIT 2



      The UnitsNet.Temperature is a struct, not a class. Will probably need a custom model binder.










      share|improve this question
















      How to use the UnitsNet nuget package in an MVC web application ?



      For example I have my object:



      public class UnitsNetTestViewModel
      {
      public int AnInput { get; set; }
      public UnitsNet.Temperature OutdoorTemperature { get; set; }
      }


      Then my view



      @model WebApplication.Models.UnitsNetTestViewModel
      @using (Html.BeginForm())
      {
      @Html.AntiForgeryToken()

      @Html.LabelFor(model => model.AnInput)
      @Html.EditorFor(model => model.AnInput)
      <br/>

      @Html.LabelFor(model => model.OutdoorTemperature)
      @Html.EditorFor(model => model.OutdoorTemperature)
      <button type="submit">Submit</button>
      }


      In my controller



          public class UnitsNetTestController : Controller
      {
      // GET: UnitNetsTest
      public ActionResult Index()
      {
      var model = new Models.UnitsNetTestViewModel {OutdoorTemperature = Temperature.FromDegreesFahrenheit(80)};
      return View("~/Views/UnitsNetTest.cshtml", model);
      }

      [HttpPost]
      public ActionResult Index(Models.UnitsNetTestViewModel model)
      {
      if (ModelState.IsValid)
      {
      return View("~/Views/Home/Index.cshtml");
      }
      return View("~/Views/UnitsNetTest.cshtml", model);
      }
      }


      I have tried using EditorFor or TextBoxFor.
      I have also tried binding on a different part of the object:



      model => model.OutdoorTemperature.Value
      model => model.OutdoorTemperature.DegreesFahrenheit
      model => model.OutdoorTemperature


      Even when using the EditorFor model.OutdoorTemperature combination, I get the full object input fields, when I update a value, it always return as zero in the controller submit.



      What Am I doing wrong ?



      Thanks.



      EDIT 1



      Trying to understand how the UnitsNet property is working, I added a subclass to my model to see if my subclass value will be available back in the controller (even if I already know that it will work). What I have notice from that : in the watch, the Value of my model.Other property is {...WebApplication.Models.SubClass} and the type is also ...WebApplication.Models.SubClass. But for model.OutdoorTemperature, the Value is {0 K} and the Type is UnitsNet.Temperature.
      Could it be a clue ?



      Here is a print screen:
      Debugging Watch Printscreen



      Updated class:



      public class UnitsNetTestViewModel
      {
      public int AnInput { get; set; }
      public UnitsNet.Temperature OutdoorTemperature { get; set; }
      public SubClass Other { get; set; }
      }

      public class SubClass
      {
      public int Value { get; set; }
      public int MySubClassValue { get; set; }
      }


      Updated View:



      @model WebApplication.Models.UnitsNetTestViewModel
      @using (Html.BeginForm())
      {
      @Html.AntiForgeryToken()

      @Html.LabelFor(model => model.AnInput)
      @Html.EditorFor(model => model.AnInput)
      <br />

      @Html.LabelFor(model => model.OutdoorTemperature)
      @Html.TextBoxFor(model => model.OutdoorTemperature.Value)

      <br />
      @Html.LabelFor(model => model.Other)
      @Html.TextBoxFor(model => model.Other.Value)

      <br />
      @Html.LabelFor(model => model.Other)
      @Html.TextBoxFor(model => model.Other.MySubClassValue)


      <button type="submit">Submit</button>
      }


      EDIT 2



      The UnitsNet.Temperature is a struct, not a class. Will probably need a custom model binder.







      c# model-view-controller






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 21 '18 at 13:48







      mp9007

















      asked Nov 20 '18 at 21:21









      mp9007mp9007

      2015




      2015
























          1 Answer
          1






          active

          oldest

          votes


















          0














          Finally, the default binding of MVC was not working because UnitsNet are struct.



          I did a custom property binder.



          I use this post as a reference : http://www.stevencwilliams.com/2015/10/26/custom-property-binding-in-asp-net-mvc/



          Here is the code that get my exemple working:



          public class TemperatureModelBinder : IPropertyBinder
          {
          public object BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
          {
          var propertyValue = controllerContext.HttpContext.Request.Form[propertyDescriptor.Name];
          double.TryParse(propertyValue, out var result);

          return UnitsNet.Temperature.FromDegreesFahrenheit(result);
          }
          }

          public interface IPropertyBinder
          {
          object BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor);
          }

          [AttributeUsage(AttributeTargets.Property)]
          public class PropertyBinderAttribute : Attribute
          {
          public Type BinderType { get; private set; }

          public PropertyBinderAttribute(Type binderType)
          {
          BinderType = binderType;
          }

          public IPropertyBinder GetBinder()
          {
          return (IPropertyBinder)DependencyResolver.Current.GetService(BinderType);
          }
          }

          public class ModelBinderBase : DefaultModelBinder
          {
          protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
          {
          PropertyBinderAttribute attribute = propertyDescriptor.Attributes
          .OfType<PropertyBinderAttribute>()
          .SingleOrDefault();
          if (attribute == null)
          {
          base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
          }
          else
          {
          propertyDescriptor.SetValue(bindingContext.Model, attribute.GetBinder().BindProperty(controllerContext, bindingContext, propertyDescriptor));
          }
          }
          }


          In my model, I added my binder attribute



              [PropertyBinder(typeof(TemperatureModelBinder))]
          public UnitsNet.Temperature OutdoorTemperature { get; set; }


          And in Global.asax.cs, Application_Start()



          ModelBinders.Binders.DefaultBinder = new ModelBinderBase();





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53401720%2funitsnet-how-to-use-it-in-mvc%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            Finally, the default binding of MVC was not working because UnitsNet are struct.



            I did a custom property binder.



            I use this post as a reference : http://www.stevencwilliams.com/2015/10/26/custom-property-binding-in-asp-net-mvc/



            Here is the code that get my exemple working:



            public class TemperatureModelBinder : IPropertyBinder
            {
            public object BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
            {
            var propertyValue = controllerContext.HttpContext.Request.Form[propertyDescriptor.Name];
            double.TryParse(propertyValue, out var result);

            return UnitsNet.Temperature.FromDegreesFahrenheit(result);
            }
            }

            public interface IPropertyBinder
            {
            object BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor);
            }

            [AttributeUsage(AttributeTargets.Property)]
            public class PropertyBinderAttribute : Attribute
            {
            public Type BinderType { get; private set; }

            public PropertyBinderAttribute(Type binderType)
            {
            BinderType = binderType;
            }

            public IPropertyBinder GetBinder()
            {
            return (IPropertyBinder)DependencyResolver.Current.GetService(BinderType);
            }
            }

            public class ModelBinderBase : DefaultModelBinder
            {
            protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
            {
            PropertyBinderAttribute attribute = propertyDescriptor.Attributes
            .OfType<PropertyBinderAttribute>()
            .SingleOrDefault();
            if (attribute == null)
            {
            base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
            }
            else
            {
            propertyDescriptor.SetValue(bindingContext.Model, attribute.GetBinder().BindProperty(controllerContext, bindingContext, propertyDescriptor));
            }
            }
            }


            In my model, I added my binder attribute



                [PropertyBinder(typeof(TemperatureModelBinder))]
            public UnitsNet.Temperature OutdoorTemperature { get; set; }


            And in Global.asax.cs, Application_Start()



            ModelBinders.Binders.DefaultBinder = new ModelBinderBase();





            share|improve this answer




























              0














              Finally, the default binding of MVC was not working because UnitsNet are struct.



              I did a custom property binder.



              I use this post as a reference : http://www.stevencwilliams.com/2015/10/26/custom-property-binding-in-asp-net-mvc/



              Here is the code that get my exemple working:



              public class TemperatureModelBinder : IPropertyBinder
              {
              public object BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
              {
              var propertyValue = controllerContext.HttpContext.Request.Form[propertyDescriptor.Name];
              double.TryParse(propertyValue, out var result);

              return UnitsNet.Temperature.FromDegreesFahrenheit(result);
              }
              }

              public interface IPropertyBinder
              {
              object BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor);
              }

              [AttributeUsage(AttributeTargets.Property)]
              public class PropertyBinderAttribute : Attribute
              {
              public Type BinderType { get; private set; }

              public PropertyBinderAttribute(Type binderType)
              {
              BinderType = binderType;
              }

              public IPropertyBinder GetBinder()
              {
              return (IPropertyBinder)DependencyResolver.Current.GetService(BinderType);
              }
              }

              public class ModelBinderBase : DefaultModelBinder
              {
              protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
              {
              PropertyBinderAttribute attribute = propertyDescriptor.Attributes
              .OfType<PropertyBinderAttribute>()
              .SingleOrDefault();
              if (attribute == null)
              {
              base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
              }
              else
              {
              propertyDescriptor.SetValue(bindingContext.Model, attribute.GetBinder().BindProperty(controllerContext, bindingContext, propertyDescriptor));
              }
              }
              }


              In my model, I added my binder attribute



                  [PropertyBinder(typeof(TemperatureModelBinder))]
              public UnitsNet.Temperature OutdoorTemperature { get; set; }


              And in Global.asax.cs, Application_Start()



              ModelBinders.Binders.DefaultBinder = new ModelBinderBase();





              share|improve this answer


























                0












                0








                0







                Finally, the default binding of MVC was not working because UnitsNet are struct.



                I did a custom property binder.



                I use this post as a reference : http://www.stevencwilliams.com/2015/10/26/custom-property-binding-in-asp-net-mvc/



                Here is the code that get my exemple working:



                public class TemperatureModelBinder : IPropertyBinder
                {
                public object BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
                {
                var propertyValue = controllerContext.HttpContext.Request.Form[propertyDescriptor.Name];
                double.TryParse(propertyValue, out var result);

                return UnitsNet.Temperature.FromDegreesFahrenheit(result);
                }
                }

                public interface IPropertyBinder
                {
                object BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor);
                }

                [AttributeUsage(AttributeTargets.Property)]
                public class PropertyBinderAttribute : Attribute
                {
                public Type BinderType { get; private set; }

                public PropertyBinderAttribute(Type binderType)
                {
                BinderType = binderType;
                }

                public IPropertyBinder GetBinder()
                {
                return (IPropertyBinder)DependencyResolver.Current.GetService(BinderType);
                }
                }

                public class ModelBinderBase : DefaultModelBinder
                {
                protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
                {
                PropertyBinderAttribute attribute = propertyDescriptor.Attributes
                .OfType<PropertyBinderAttribute>()
                .SingleOrDefault();
                if (attribute == null)
                {
                base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
                }
                else
                {
                propertyDescriptor.SetValue(bindingContext.Model, attribute.GetBinder().BindProperty(controllerContext, bindingContext, propertyDescriptor));
                }
                }
                }


                In my model, I added my binder attribute



                    [PropertyBinder(typeof(TemperatureModelBinder))]
                public UnitsNet.Temperature OutdoorTemperature { get; set; }


                And in Global.asax.cs, Application_Start()



                ModelBinders.Binders.DefaultBinder = new ModelBinderBase();





                share|improve this answer













                Finally, the default binding of MVC was not working because UnitsNet are struct.



                I did a custom property binder.



                I use this post as a reference : http://www.stevencwilliams.com/2015/10/26/custom-property-binding-in-asp-net-mvc/



                Here is the code that get my exemple working:



                public class TemperatureModelBinder : IPropertyBinder
                {
                public object BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
                {
                var propertyValue = controllerContext.HttpContext.Request.Form[propertyDescriptor.Name];
                double.TryParse(propertyValue, out var result);

                return UnitsNet.Temperature.FromDegreesFahrenheit(result);
                }
                }

                public interface IPropertyBinder
                {
                object BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor);
                }

                [AttributeUsage(AttributeTargets.Property)]
                public class PropertyBinderAttribute : Attribute
                {
                public Type BinderType { get; private set; }

                public PropertyBinderAttribute(Type binderType)
                {
                BinderType = binderType;
                }

                public IPropertyBinder GetBinder()
                {
                return (IPropertyBinder)DependencyResolver.Current.GetService(BinderType);
                }
                }

                public class ModelBinderBase : DefaultModelBinder
                {
                protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
                {
                PropertyBinderAttribute attribute = propertyDescriptor.Attributes
                .OfType<PropertyBinderAttribute>()
                .SingleOrDefault();
                if (attribute == null)
                {
                base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
                }
                else
                {
                propertyDescriptor.SetValue(bindingContext.Model, attribute.GetBinder().BindProperty(controllerContext, bindingContext, propertyDescriptor));
                }
                }
                }


                In my model, I added my binder attribute



                    [PropertyBinder(typeof(TemperatureModelBinder))]
                public UnitsNet.Temperature OutdoorTemperature { get; set; }


                And in Global.asax.cs, Application_Start()



                ModelBinders.Binders.DefaultBinder = new ModelBinderBase();






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 21 '18 at 14:51









                mp9007mp9007

                2015




                2015






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53401720%2funitsnet-how-to-use-it-in-mvc%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    MongoDB - Not Authorized To Execute Command

                    How to fix TextFormField cause rebuild widget in Flutter

                    Npm cannot find a required file even through it is in the searched directory