Asp.net @model.Name和@Html.DisplayFor(m=>;model.Name)之间的差异
我正在开发web应用程序,这是我第一次使用asp.net mvc core 2.0。 我从任何教程中学习,但无论在哪里,模型打印都有不同的方法,我不明白为什么有很多方法可以只打印 这两种方法的区别是什么:Asp.net @model.Name和@Html.DisplayFor(m=>;model.Name)之间的差异,asp.net,asp.net-core,Asp.net,Asp.net Core,我正在开发web应用程序,这是我第一次使用asp.net mvc core 2.0。 我从任何教程中学习,但无论在哪里,模型打印都有不同的方法,我不明白为什么有很多方法可以只打印 这两种方法的区别是什么: <td> @item.Name </td> <td> @Html.DisplayFor(modelItem => item.Name) </td> @项目名称 @DisplayFor(modelItem=>item.Nam
<td>
@item.Name
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
@项目名称
@DisplayFor(modelItem=>item.Name)
哪一个更好?如果您有任何给定数据类型的自定义显示模板,则使用
@Html.DisplayFor()
将尊重该自定义显示模板,并根据需要呈现代码
直接使用@Model.YourField
只需在该字段上调用.ToString()
,并输出该调用返回的任何内容
试试这个:
模型/IndexModel.cs:
public class IndexModel
{
public DateTime HireDate { get; set; }
}
public ActionResult Index()
{
IndexModel model = new IndexModel {HireDate = new DateTime(2015, 8, 15)};
return View(model);
}
<div class="row">
<div class="col-md-6 col-md-offset-2">
Output directly: @Model.HireDate
<br/><br/>
Output via DisplayFor: @Html.DisplayFor(m => m.HireDate)
</div>
</div>
@{
<span class="datetime">@Model.ToString("MMM dd, yyyy / HH:mm")</span>
}
控制器/HomeController.cs:
public class IndexModel
{
public DateTime HireDate { get; set; }
}
public ActionResult Index()
{
IndexModel model = new IndexModel {HireDate = new DateTime(2015, 8, 15)};
return View(model);
}
<div class="row">
<div class="col-md-6 col-md-offset-2">
Output directly: @Model.HireDate
<br/><br/>
Output via DisplayFor: @Html.DisplayFor(m => m.HireDate)
</div>
</div>
@{
<span class="datetime">@Model.ToString("MMM dd, yyyy / HH:mm")</span>
}
视图/Home/Index.cshtml:
public class IndexModel
{
public DateTime HireDate { get; set; }
}
public ActionResult Index()
{
IndexModel model = new IndexModel {HireDate = new DateTime(2015, 8, 15)};
return View(model);
}
<div class="row">
<div class="col-md-6 col-md-offset-2">
Output directly: @Model.HireDate
<br/><br/>
Output via DisplayFor: @Html.DisplayFor(m => m.HireDate)
</div>
</div>
@{
<span class="datetime">@Model.ToString("MMM dd, yyyy / HH:mm")</span>
}
现在哪一个更好取决于你想做什么:
- 通常,我更喜欢使用
,因为通常情况下,如果我遇到了定义自定义显示模板的麻烦,我可能也希望使用它@Html.DisplayFor()
- 但是,如果您只需要“原始”输出,而不需要自定义渲染,则也可以直接使用
@model.YourField
因此,这实际上是一个你想要/需要什么的问题——选择一个最适合你的需要/要求的 我不是ASP.NET MVC的真正大师,但我相信
@model.Name
符号只是输出数据,可能在值上使用.ToString()
,而@Html.DisplayFor()
将为类型使用配置的输出呈现模板。因此,如果您为所有DateTime
值定义了一个输出呈现模板,那么无论何时使用@Html.DisplayFor()
,它都会被应用,但如果您直接使用@model,它不会影响您的输出。YourDate
在这里阅读关于ASP.NET MVC显示模板的内容:@marc_,哇,这是一个非常有用的链接,感谢您使用lotUsing@Model.YourField直接调用该字段上的.ToString(),并输出该调用返回的任何内容IIRC。这还将围绕MvcString
类包装字符串,该类将正确地转义字符串(即替换
等),或者无法准确地记住,如果它是一个。它对输入进行编码以防止html和scrip注入。