Reputation: 3759
I'm trying to just display a value in my Razor code. I've tried both DisplayFor and LabelFor. If I use DisplayFor then my value shows up but my CSS doesn't get applied. If I use LabelFor then it's the opposite, my CSS is applied but the text only displays as "EmployeeId". I've confirmed that my ViewModel has a value populated for the EmployeeId prior to going to View.
This is what I've tried:
<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>
Upvotes: 2
Views: 2418
Reputation: 2107
This will work:
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);
}
View:
@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>
Upvotes: 0
Reputation: 4693
first of all DisplayFor does not have an overload of htmlAttributes
so new { @class = "control-label label-value" }
wont work and secondly LabelFor does not display value of the property it will just display the name of the property so
you can do it like this
<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>
Upvotes: 5