How to assign and use variable in MVC Razor View

asp.net-mvc, razor

Solution

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.

Problem

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?

Original source