Question

Our database stores values along with their associated format. Some number have 0 numbers after the decimal, some 1, some are currency, etc.

I am trying to avoid doing the following in each instance the data needs to be displayed.

@foreach (var i in Model.CandidateHireGoalsAndActivity)
{
    if (i.DataTypeId == 3)
    { 
        <tr>
            <td>@i.HireGoalName</td>
            <td>@i.ActivityValue.ToString("C0")</td>
            <td>@i.GoalValue.ToString("C0")</td>
        </tr>
    }
    else if (i.DataTypeId == 2)
    { 
        <tr>
            <td>@i.HireGoalName</td>
            <td>@i.ActivityValue.ToString("F2")</td>
            <td>@i.GoalValue.ToString("F2")</td>
        </tr>
    }
    else if....(etc)
}

I am trying to write a basic extension method that receives a string and desired format and then my code could look more like this.

    @foreach (var i in Model.CandidateHireGoalsAndActivity)
    {
       <tr>
          <td>@i.HireGoalName</td>
          <td>@Html.FormatString(i.ActivityValue.ToString(), i.DataTypeId)</td>
          <td>@Html.FormatString(i.GoalValue.ToString(), i.DataTypeId)</td>
       </tr>
    }

For some reason, the string coming out of my helper is never formatted. Whatever unformatted number I pass in is passed back out. I am not sure what I am doing wrong or missing.

helper method:

public static MvcHtmlString FormatString(this HtmlHelper helper, string stringToFormat, int format)
        {
            if (format == 3)
            {
                return MvcHtmlString.Create(String.Format("{0:C0}", stringToFormat));      
            }
            return MvcHtmlString.Create(String.Format("{0:0}", stringToFormat));
        }

I've also tried returning a regular string instead of the MvcHtmlString as well as using the ToString() method, but neither helped.

Any help/suggestions are much appreciated.

Thanks, -Tim

Was it helpful?

Solution

Your error here is you are trying to format a string, not a number. String.Format() can format only if you pass a number. So you just simply need to change parameter from string to double:

public static MvcHtmlString FormatString(this HtmlHelper helper, double numberToFormat, int format)

And don't convert numbers in the view:

@Html.FormatString(i.ActivityValue, i.DataTypeId)

If you have not only double values, but also other types (like float or decimal) you can use object instead of double:

public static MvcHtmlString FormatString(this HtmlHelper helper, object numberToFormat, int format)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top