7

I've identified several of my views that require some simple logic, for example to add a class to a set of controls created with @Html helpers. I've tried several different ways, but they either throw errors in the View or just don't work.

A simple example:

Assign variable:

@if( condition ) { var _disabled = "disabled"; } @Html.CheckBoxFor(m => m.Test, new { @class = "form-control " + @_disabled }) 

Or:

@if( condition ) { var _checked = "checked"; } @Html.CheckBoxFor(m => m.Test, new { @checked = @_checked }) 

Of course, these doesn't work. I'm just trying to eliminate a bunch of @if conditions in my Views, but I have other lightweight logic uses for using variables. My problem might be more of how to use a variable in this way than actually assigning it?

2 Answers 2

9

It would seem that you're understanding razor fine. The problem with your code seems to be that you're using a variable out of scope. You can't define a variable inside an if statement, and then use it outside, because the compiler won't know for sure that the variable outside actually exists.

I would suggest the following:

@{ var thing = "something";//variable defined outside of if block. you could just say String something; without initializing as well. if(condition){ thing = "something else"; } } @Html.Raw(thing);//or whatever 

As a side note, (in my opinion) it's better to do stuff in the controllers when you can, rather than the views. But if things make more sense in the views, just keep them there. (-:

Hope this helps.

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

Comments

5

Try this;

@{ var disabled = string.Empty; if (true) { disabled = "disabled"; } } @Html.CheckBoxFor(m => m.RememberMe, new { @class = "form-control " + disabled }) 

Thanks!

2 Comments

Saranga, I know your answer is right and it helps me out. Thank you. I see now that (at least in my example) I assigned the variable within the if block as Jack pointed out. I'm not sure I did it that way when I was actually testing. Anyway, thx.
I'm happy if it helped you rwkiii.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.