3

I'm reading percentages from a database, then use that number to create a bar showing visual progress. I need to do something like this on my aspx page:

       <%  
       if (ViewData["width"] != null){
        <div style="width: <%: ViewData["width"] %>px;"
       </div>
       }%>

Of course the above method doesn't work, but hopefully you can see what im trying to achieve. How do i change style attributes dynamically in ASP.NET MVC?

2 Answers 2

10

You just wrote HTML in the middle of a code block. You need to put your HTML outside the code block.

<% if (ViewData["width"] != null) { %>
    <div style="width: <%: ViewData["width"] %>px;"></div>
<% } %>

Alternatively, you could switch to the Razor language which does away with all the <% %>s and allows you to intersperse C# and HTML much easier. It looks like this:

@if (ViewBag.width != null) {
    <div style="width: @(ViewBag.width)px;"></div>
}
Sign up to request clarification or add additional context in comments.

5 Comments

This is MVC2 so I cant use ViewBag. Also, this will be a result set with numerous results, so i need the HTML inside the code block as i'll be looping through a for statement. Unless i'm misunderstanding what you're saying
@userrandomnumbers: The HTML will still be inside the if statement (and any other control structures). Just outside the part that's interpreted as C#. Try it!
You know what, my method did work. I never tested it. My code didnt change color and it looked like a comment.
@userrandomnumbers: I'm finding that a bit hard to believe as it has a syntax error. You sure you didn't miscopypaste it to SO?
I only posted a snippet of my code. No reason to bog everyone down with a bunch of irrelevant code.
1

Your method should work, you just need to put the div code outside of the server block.

<% if (ViewData["width"] != null){ %>
    <div style="width: <%: ViewData["width"] %>px;"
    </div>
<% } %>

Comments

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.