2017-04-26 62 views
1

我想在我的Razor代码中显示一个值。我已经尝试了DisplayFor和LabelFor。如果我使用DisplayFor,那么我的值显示,但我的CSS不适用。如果我使用LabelFor则相反,我的CSS已应用,但文本仅显示为“EmployeeId”。我已经确认我的ViewModel在去View之前为EmployeeI填充了一个值。LabelFor不显示值?

这是我已经试过:

<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> 

回答

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

仅供参考:'DisplayFor'是*模板* -helper。这意味着,输出是基于“显示模板”的。大多数属性类型的默认显示模板只是输出没有HTML的值。因此,即使它实际上允许你传递参数,也没有什么可以应用'htmlAttributes'参数。你可以创建自己的自定义显示模板并包含HTML,但由于它是一个自定义模板,因此您需要负责用于手动设置HTML上的属性。 'DisplayFor'接受'additionalViewData',你可以使用它来传递值。 –

+0

谢谢,这些答案似乎是正确的,但它看起来像DisplayFor是我所需要的。我很欣赏所有额外的信息,以便我真正理解两位助手之间的差异。 – Caverman

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>