MVC,Razor,CSS和Dynamic Div ID

时间:2018-03-17 18:51:51

标签: html css asp.net-mvc razor

我遇到了MVC的问题,对象的CSS和基于名称的id处理它。

我拥有的是

@foreach (var item in Model)
        {
        <div class="row d-flex">
            <div class="col my-0 my-md-5 position-relative category-container p-0 p-sm-3 d-inline-block">
                <div id^=@item.Description class="category mx-auto">
                    @Html.ActionLink(@item.Description], "LoadById", new { id = item.Id })

                </div>

             </div>
         </div>

    }

CSS设置为引用“id”应具有的文本,IE桌面,笔记本电脑等。 我创建了一个字符串[]并将其分配给item.Description 然后尝试在css中引用字符串名称a [0],但它也没有看到。 有没有办法让CSS找到ID变量以正确处理格式?

我已经/试过的CSS是

 #dashboard #Desktops {
    background-image: url("../images/dashboardImages/real/desktops.jpg");
}
 #dashboard #a[0] {
    background-image: url("../images/dashboardImages/real/desktops.jpg");
}

1 个答案:

答案 0 :(得分:0)

这是一个供您使用的模板,我希望您能够根据您所描述的内容进行调整,这可以根据您的具体需要进行调整。

的ViewModels:

public class TestPageViewModel
{
    // Include a list (IEnumerable) of your item model
    public IEnumerable<TestItemViewModel> TestModelItems { get; set; }
}
public class TestItemViewModel
{
    public int Id { get; set; }
    public string Css { get; set; }
    public string Description { get; set; }
}

在视图的控制器操作中:

// Make the list of items (using a method of your choice)
var modelItems = new List<TestItemViewModel>
{
    new TestItemViewModel { Id = 1000, Css = "laptops", Description = "Laptops Category" },
    new TestItemViewModel { Id = 1001, Css = "desktops", Description = "Desktops Category" },
};
// Assign model items to the page View Model
var viewModel = new TestPageViewModel {
    TestModelItems = modelItems
};

在视图中:

<div id="dashboard">
    @foreach (var item in Model.TestModelItems)
    {
        <div class="row d-flex">
            <div class="col my-0 my-md-5 position-relative category-container p-0 p-sm-3 d-inline-block">
                <!-- Reference the item.Css, item.Id or combinations of the two -->
                <div id="@item.Id" class="category mx-auto @item.Css @item.Css-@item.Id">
                    @Html.ActionLink(item.Description, "LoadById", new { id = item.Id })
                </div>
            </div>
        </div>
    }
</div>

Css示例(适应口味):

#dashboard .laptops a{
    color: green;
}
#dashboard .desktops a{
    color: blue;
}
#dashboard .laptops-1000{
    background-color: yellow;
    padding:5px;
}
#dashboard .desktops-1001{
    background-color: cyan;
    padding:5px;
}