ety
ety

Reputation: 75

asp.net mvc razor Get integer part of string

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?

Upvotes: 1

Views: 1063

Answers (1)

David
David

Reputation: 218808

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.

Upvotes: 3

Related Questions