Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a value type in strongly typed MVC view user control

Tags:

c#

asp.net-mvc

I've got an MVC user control with the following basic structure:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Decimal>" %>

<%= Math.Round(Model) %>

Which gives this error message when I use it:

Compiler Error Message: CS0452: The type 'decimal' must be a reference type in order to use it as parameter 'TModel' in the generic type or method 'System.Web.Mvc.ViewUserControl'

Is there a way to get this to work (somehow tricking the framework into treating the Decimal as a reference type maybe?) Or is what I'm trying to do just fundamentally wrong?

like image 665
kristian Avatar asked Dec 01 '22 07:12

kristian


1 Answers

I would suggest you wrap the value type within a ViewModel. This will allow for some flexibility in the future (which may or may not be needed).

public class MyUserControlViewModel
{
    public Decimal MyValue { get; private set; }

    public MyUserControlViewModel(Decimal dec)
    {
        MyValue = dec;
    }
}


<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyUserControlViewModel>" %>

<%= Math.Round(Model.MyValue) %>
like image 149
Jon Erickson Avatar answered Dec 04 '22 10:12

Jon Erickson