[英]What is a simple explanation for displayfor and displaynamefor in asp.net?
我有一堂課
public class Item
{
public int ItemId { get; set; }
[Required(ErrorMessage = "Category is required")]
[Range(1, int.MaxValue, ErrorMessage = "Category is required")]
public int CategoryId { get; set; }
[Display(Name = "Current password")]
[Required(ErrorMessage = "Name is required")]
[StringLength(160)]
public string Name { get; set; }
[Required(ErrorMessage = "Price is required")]
[Range(0.01, 100.00,
ErrorMessage = "Price must be between 0.01 and 100.00")]
public decimal Price { get; set; }
public virtual Category Category { get; set; }
}
在我的控制器中,我傳遞了一個實例來查看
public ActionResult Index()
{
var model = new Item
{
CategoryId = 1,
Name = "aaa",
Price = 2
};
return View("Index", model);
}
然后在視圖中我嘗試使用顯示名稱
@model GenericShop.Models.Item
<p>
@Html.DisplayNameFor(m => m.Name)
</p>
並得到以下錯誤
編譯器錯誤消息:CS1061:“System.Web.Mvc.HtmlHelper”不包含“DisplayNameFor”的定義,並且找不到接受“System.Web.Mvc.HtmlHelper”類型的第一個參數的擴展方法“DisplayNameFor”(您是否缺少 using 指令或程序集引用?)
@Html.DisplayFor(m => m.Name)
工作正常,但我不明白為什么
@Html.DisplayNameFor(m => m.Name)
沒有。
DisplayFor
顯示模型項的值,而DisplayNameFor
只顯示屬性的名稱?
差不多好了。 :)
DisplayNameFor 顯示屬性的名稱或在屬性的顯示屬性中定義的字符串。
public class Item
{
public int ItemId { get; set; }
[Display(Name = "Current name")]
[Required(ErrorMessage = "Name is required")]
[StringLength(160)]
public string Name { get; set; }
[Required(ErrorMessage = "Price is required")]
[Range(0.01, 100.00,
ErrorMessage = "Price must be between 0.01 and 100.00")]
public decimal Price { get; set; }
}
然后@Html.DisplayNameFor(m => m.Name)
將顯示“當前名稱”。
@Html.DisplayNameFor(m => m.Price)
只會顯示價格。
請注意,您還可以像這樣本地化 display 屬性:
[Display(ResourceType = typeof(MyResources), Name = "Name")]
public string Name{ get; set; }
這又將在 MyResources resc 文件中查找。 (如果設置正確)。
Html.DisplayFor 顯示字段的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.