1

I have a property string in my model with values like "USD 32", "E 123" ... and I need the integer part of those strings ("32", "123", ...)

@{
    var number = @Model.MyStringProperty;
}

ideas?

1 Answer 1

3

Don't do this in Razor, or in the View at all. This belongs squarely on the Model.

For example, let's assume the property looks like this:

public string MyStringProperty { get; set; }

Then what you would do is add another property to transform the value from this one:

public int MyStringPropertyAsInt
{
    get
    {
        // string manipulation logic goes here
        // possibly something like this:
        var numericString = new string(MyStringProperty.Where(x => char.IsDigit(x)).ToArray());
        var integerValue = 0;
        int.TryParse(numericString, out integerValue);
        return integerValue;
    }
}

Then in the View, you'd simply reference that property:

@Model.MyStringPropertyAsInt

The point is, you shouldn't have a lot of server-side code blocks in the View. Ideally all of the data manipulation and logic is on the Model, and the View simply binds to that Model's exposed data properties.

Sign up to request clarification or add additional context in comments.

2 Comments

Looking at the examples given in the question, it would be worth splitting the original string value into two properties. One string property for the currency code, and an integer field for the amount (though if you are dealing with money a Decimal would be better).
@PervezChoudhury: Agreed. Though he did specify the "integer part of the string." The more strongly-typed and structured the data, the better. Ideally the "units" and the "amount" should be separate data altogether.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.