tags:

views:

44

answers:

2

I'm using MVC and in my View I'm assigning classes to various divs, etc using the values of certain properties within my View Model.

However, these values contain spaces and I need to remove the spaces before rendering the HTML.

Is there another way of doing this?

<% Response.Write(benefit.Name.Replace(" ","")); %>
+1  A: 

If you think about it, the code in your view is just editing a string. So a basic Replace as you have done is how I would do it.

However, why not do the work in your model, ie provide properties that return the trimmed string? Or better still, a method? EG:

<%: Model.ReplaceWS(benefit.Name); %>

Where:

public string ReplaceWS(string s)
{
   s = s.Replace(" ", "");
   return s;
}

If nothing else, this looks neater and makes the view easier to read.

You could also create an extension method for string (You could limit visibility by using a given namespace in the extension method definition)

That way you could write:

<%: benefit.Name.ReplaceWS(); %>

I think that is my preferred option, as it expresses what you are doing

awrigley
If working with mvc 1, as opposed to mvc 2, use: <%= instead of <%: Also, be careful if, for example, benefit.Name comes from user input. This could lead XSS attacks.
awrigley
In that case, you have to explicitly html encode the string. With mvc 2, <%: does this for you.
awrigley
A: 

Using string's Replace method is fine. Another option would be to use a Regex, but that's more complicated.

However, you shouldn't really be using Response.Write in ASP.NET MVC templates - there is an output delimiter tag '<%:' for that:

<%: benefit.Name.Replace(" ","") %>

Note that you don't need the semi-colon when using the '<%:' tag.

Isn't that more succinct already?

Note: You should use '<%=' in MVC 1, and '<%:' in MVC 2. The latter sanitises strings to prevent XSS attacks.

Scott Lowe
You should use html encoding in mvc 1!
awrigley
I guess with these answers it always a case of 'how deep do you go?'. But yeah, that's a good point :-)
Scott Lowe