我正试图在我的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>
答案 0 :(得分:2)
首先,DisplayFor没有htmlAttributes
的重载,因此new { @class = "control-label label-value" }
无法正常工作,其次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>
答案 1 :(得分:0)
这将有效:
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>