Using value type in strongly typed MVC view user control

I have a custom MVC control with the following basic structure:

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

<%= Math.Round(Model) %>

What gives this error message when I use it:

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

Is there a way to make this work (somehow cheating on the structure to handle the decimal as a reference type?) Or is this what I'm trying to do wrong in the root?

+3
source share
7 answers

ViewModel. ( ).

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) %>
+7

, ,

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

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

+4

ViewUserControl :

public class ViewUserControl<TModel> : ViewUserControl
where TModel : class

, . Decimal .

+3

:

 public class Wrapper
{
        public Wrapper(decimal d)
        {
            this.Value = d;   
        }
        Decimal Value { get; set; }
}

:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Wrapper>" %>
<%= Math.Round(Model.Value) %>
+2

- DTO . DTO . , Math.Round .

+1

ASP.Net MVC Framework, , , , .

, , :

class MyDouble : Model   // or whatever MVC calls it Model
{
   public TheValue {
     get;
     set;
   }
}

<%= Math.Round(Model.TheValue) %>.

. , . , , , .

0

While I strongly support all of the above answers, stating that to round the decimal value in the class to support further development, you can quickly solve your problem by making the decimal value NULL ("decimal?"), Since System.Nullable is a reference type .

0
source

Source: https://habr.com/ru/post/1708425/


All Articles