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?
Variables are declared using the var keyword, or by using the type (if you want to declare the type), but ASP.NET can usually determine data types automatically.
Using the Razor syntax, write the characters string array variable value to the view within the provided <ul> element. Use a foreach loop to render each characters string array value within its own <li> element. Name your loop value variable character. Be sure to remove the placeholder <!
Declaring (Creating) Variablestype variableName = value; Where type is a C# type (such as int or string ), and variableName is the name of the variable (such as x or name). The equal sign is used to assign values to the variable.
Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine.
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.
Try this;
@{
var disabled = string.Empty;
if (true)
{
disabled = "disabled";
}
}
@Html.CheckBoxFor(m => m.RememberMe, new { @class = "form-control " + disabled })
Thanks!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With