在asp.net中,displayfor和displaynamefor的简单解释是什么? [英] 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; }
}
在我的控制器中,我将其实例传递给视图
In my controller I pass an instance of this to view
public ActionResult Index()
{
var model = new Item
{
CategoryId = 1,
Name = "aaa",
Price = 2
};
return View("Index", model);
}
然后在视图中我尝试使用显示名称
then in view I try to display name using
@model GenericShop.Models.Item
<p>
@Html.DisplayNameFor(m => m.Name)
</p>
并出现以下错误
编译器错误消息:CS1061: 'System.Web.Mvc.HtmlHelper'不包含 "DisplayNameFor"的定义,没有扩展方法 'DisplayNameFor'接受类型的第一个参数 可以找到"System.Web.Mvc.HtmlHelper" (您是否缺少using指令或程序集引用?)
Compiler Error Message: CS1061: 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'DisplayNameFor' and no extension method 'DisplayNameFor' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)
@Html.DisplayFor(m => m.Name)
可以正常工作,但是我看不到为什么
@Html.DisplayFor(m => m.Name)
works fine, but I just cant see why
@Html.DisplayNameFor(m => m.Name)
没有.
DisplayFor
显示模型项的值,而DisplayNameFor
仅显示属性的名称?
DisplayFor
displays the value for the model item and DisplayNameFor
simply displays the name of the property?
推荐答案
快到了. :)
DisplayNameFor显示属性的名称或在属性的display属性中定义的字符串.
The DisplayNameFor shows the name of the property or the string defined in the display attribute for the property.
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)
将显示当前名称".
Then @Html.DisplayNameFor(m => m.Name)
would show 'Current name'.
@Html.DisplayNameFor(m => m.Price)
只会显示价格.
请注意,您还可以像这样本地化显示属性:
Note that you can also localize the display attribute like this:
[Display(ResourceType = typeof(MyResources), Name = "Name")]
public string Name{ get; set; }
依次将在MyResources resc文件中查找. (如果安装正确完成).
Which in turn will look in the MyResources resc file. (If setup is done correctly).
Html.DisplayFor显示字段的值.
The Html.DisplayFor shows the value of the field.
这篇关于在asp.net中,displayfor和displaynamefor的简单解释是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!