LabelFor 不显示值?

LabelFor not displaying value?

我试图在我的 Razor 代码中显示一个值。我已经尝试过 DisplayFor 和 LabelFor。如果我使用 DisplayFor,则会显示我的值,但不会应用我的 CSS。如果我使用 LabelFor,则情况正好相反,我的 CSS 已应用,但文本仅显示为 "EmployeeId"。我已经确认我的 ViewModel 在转到 View 之前为 EmployeeId 填充了一个值。

这是我试过的:

<div class="row voffset2">
    <div class="col-md-12">
        Employee ID: @Html.LabelFor(m => m.EmployeeId, new { @class = "control-label label-value" })
    </div>
</div>

<div class="row voffset2">
    <div class="col-md-12">
        Employee ID: @Html.DisplayFor(m => m.EmployeeId, new { @class = "control-label label-value" })
    </div>
</div>

首先,DisplayFor does not have an overload of htmlAttributes so new { @class = "control-label label-value" } wont work and secondly LabelFor 不显示 属性 的值,它只会显示 属性 的名称,所以 你可以这样做

<div class="row voffset2">
    <div class="col-md-12">
        Employee ID: <span class"ontrol-label label-value">@Html.DisplayFor(m => m.EmployeeId)</span>
    </div>
</div>

这会起作用:

public class LabelViewModel
{
    [Display(Name = "Employee\nId")]
    public int EmployeeId { get; set; }

    //display for is for iterating over a collection
    public IList<string> Employees { get; set; }
}

public class HomeController : Controller
{
    public ActionResult Index54()
    {
        //display for is for iterating over a collection
        LabelViewModel labelViewModel = new LabelViewModel();
        labelViewModel.Employees = new List<string>();
        labelViewModel.Employees.Add("emp1");
        labelViewModel.Employees.Add("emp2");
        return View(labelViewModel);
    }

查看:

@model Testy20161006.Controllers.LabelViewModel
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index54</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <style type="text/css">
        .cssworks {
            color: red
        }
    </style>
</head>
<body>
    <div class="row voffset2">
        <div class="col-md-12">
            Employee ID: @Html.LabelFor(m => m.EmployeeId, new { @class = "cssworks control-label label-value" })
        </div>
    </div>

    <div class="row voffset2">
        <div class="col-md-12">
            @*display for is for iterating over a collection*@
            @*changed the next line, since you can't put a class in displayfor*@
            Employee ID: <span class="cssworks">@Html.DisplayFor(m => m.Employees)</span>
        </div>
    </div>
</body>
</html>