How to use mixed decimal/double values in dynamic views RRS feed

  • Question

  • User-1262787652 posted

    In ASP.NET MVC4 application WebMatrix is used to retrieve dynamic data.

    This data is used in Razor view expressions. Data contains decimal values and expressions are like

    value * 1.5

    Such expression causes exception if view is executed:

    operation '*' cannot applied to decimal and double values.

    How to fix this ? I tried to convert decimal values in returned data to double using method below but got compile error shown in comment since row is read only.

    Is it possible to clone returned row and replace decimal values with double values or is there some other way to use returned decimal data in razor views?

    dynamic GetConvertedRow()
    using (var db = Database.OpenConnectionString("myconnectionstring",
    IEnumerable<dynamic> res = db.Query("select * from sometables");
    var enumer = res.GetEnumerator();
    if (!enumer.MoveNext())
    throw new ApplicationException("Query must return at least one row");
    DynamicRecord row = enumer.Current;
    foreach (var p in row.Columns)
    if (row[p] is decimal?)
    // Error: Property or indexer 'WebMatrix.Data.DynamicRecord.this[string]' cannot be assigned to -- it is read only
    row[p] = Convert.ChangeType(row[p], typeof(double));
    return row;

    Wednesday, May 14, 2014 11:35 AM


  • User-760709272 posted

    If value is decimal try

    value * 1.5M

    it it is double try

    value * 1.5D

    When you just put a number like 1.5, .net chooses the type it things is most appropriate but might get it wrong.  Adding postfix like M for decimal, D for double, L for long allows you to choose the type.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 14, 2014 12:04 PM