Declare a local variable at the beginning of the View: @{ var yourStyle = “”; if(Model.Condition) { yourStyle = “float:left;”; //specific conditions and logic } else { yourStyle = “float:right;”; //any other conditions and logic } } and then just use it in your div: <div style=”@yourStyle”>
Tag: Razor
How to make a checkbox or dropdown readonly in Razor
You can add @disabled = “disabled” to the last parameter named HtmlAttributes. @Html.CheckBox(“someNameForYourCheckBox”, CheckedValue (True or Not), new { @disabled = “disabled” }) @Html.DropDownList(“someNameForYourDropDown”, YourSelectList (comes from Model), new { @disabled = “disabled” })
How to put text inside MVC Razor code block
The contents of a code block ({ … }) are expected to be code or markup (tags), not plain text. If you want to put text directly in a code block, you have three choices: Wrap it in any HTML tag Wrap it in the special Razor <text> tag, which will just render the text without the […]
How to insert space in Razor Asp.Net
@if (condition) { <text> </text> @: }
How to use ? : if statements with Asp.Net Razor
<span class=”btn btn-@(item.Value == 1 ? “primary” : item.Value == 2 ? “warning” : “danger”)”>EVALUATE</span> Briefly, we can say that @(condition ? “the value, if the condition is true” : “the value, if the condition is false” )
Getting index value in Razor ForEach
@{int i = 0;} @foreach(var myItem in Model.Members) { <span>@i</span> @{i++;} }
Populating Javascript array with Model in ASP.Net MVC Razor
We just need to loop through the razor collection to populate the Javascript array as below: @foreach (var item in Model) { @:$(function () { @:$(“#map”).googleMap(); @:$(“#map”).addMarker({ @:coords:[@item.Latitude], @:title: `@item.City, @item.District`, @:text: `@item.Address` @:}); @:}); }
Pass model from Razor view to JavaScript
Let’s say you send a model called “MyModel” from controller to view. In Controller: … var result = new MyModel() { Id = 1, Name = “Ercan”, FavoriteTeam = “Galatasaray”, FavoriteGame = “Half Life Series” } return View(result); … and now we will send this model which comes with result to Javascript via setName function: […]
@helpers in Asp.NET MVC Razor
A @helper in Razor ultimately defines a function you can invoke from anywhere inside the view. The function can output literal text and can contain code blocks and code expressions. Don’t forget that heavy amounts of code in a view can lead to grief. You have @PluralPick(Model.Count, “child”, “children”). @helper PluralPick(int amount, string singular, string […]
Using Code Blocks, Mixing Text & C# Code and Comments in Asp.NET MVC Razor
In Razor you can create blocks of code nearly anywhere using @{ }. A block of code doesn’t emit anything into the output, but you can use the block to manipulate a model, declare variables, and set local properties on a view. Be extremely careful about having too much code in a view, however, because […]