2017-04-26 60 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>