c# - 在 Razor 中将 css 与 c# mvc 混合

标签 c# css asp.net-mvc razor

我如何使用 razor 引擎 (c# mvc) 简化此代码..有什么方法可以在 razor 引擎中混合 c# 和 css 吗?

实际上我在尝试这个时没有得到正确答案

 @model FoodViewModel

@foreach (FoodView item in Model.Foodviews)
{         
 @if (item.vote == 1)
       {
        <input type="radio" name="example" class="rating" value="1"  checked="checked" />
        <input type="radio" name="example" class="rating" value="2" />
        <input type="radio" name="example" class="rating" value="3" />
        <input type="radio" name="example" class="rating" value="4" />
        <input type="radio" name="example" class="rating" value="5" />
       } 
        else if(item.vote == 2)
       {
        <input type="radio" name="example" class="rating" value="1" />
        <input type="radio" name="example" class="rating" value="2"  checked="checked"  />
        <input type="radio" name="example" class="rating" value="3" />
        <input type="radio" name="example" class="rating" value="4" />
        <input type="radio" name="example" class="rating" value="5" />
       }
       else if (@item.vote == 3)
       {
        <input type="radio" name="example" class="rating" value="1" />
        <input type="radio" name="example" class="rating" value="2" />
        <input type="radio" name="example" class="rating" value="3" checked="checked" />
        <input type="radio" name="example" class="rating" value="4" />
        <input type="radio" name="example" class="rating" value="5" />
       } 

       else
       {
        <input type="radio" name="example" class="rating" value="1" />
        <input type="radio" name="example" class="rating" value="2" />
        <input type="radio" name="example" class="rating" value="3" />
        <input type="radio" name="example" class="rating" value="4" />
        <input type="radio" name="example" class="rating" value="5"  />
       } 
}

最佳答案

你可以尝试一个简单的循环吗?

@for (var i = 1; i < 6; i++) {
    if (i == item.vote) {
        <input type="radio" name="example" class="rating" value="@i" checked>
    } else {
        <input type="radio" name="example" class="rating" value="@i">
    }
}

或者,更好的是,使用 html 助手;

@for (var i = 1; i < 6; i++) {
     @Html.RadioButton("example", i, item.vote == i, new { @class = "rating" })
}

关于c# - 在 Razor 中将 css 与 c# mvc 混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21721947/

相关文章:

c# - GZipStream 机器依赖

c# - 如何确定 .NET 中 explorer.exe 的路径?

c# - 无法捕获 System.Xaml.XamlParseException

jquery - 将边框图像与背景图像对齐;

css - 在将右 div 移动到左 div 下方之前,让左 div 包装其内容

c# - String.Format() 不起作用,但 string.Format() 起作用

html - Bootstrap 3 - 2 列具有相同的列高,同一列中有 2 个图像,一个图像与顶部对齐,一个与底部对齐

c# - EF6 存储过程必须声明标量变量

asp.net-mvc - 部署的 ASP.NET MVC 4 项目无法运行

c# - ASP.NET MVC : How to create an action filter to output JSON?