Shu*_*mov 3 asp.net asp.net-core
我正在开发web应用程序,这是我第一次使用asp.net mvc core 2.0.我正在学习任何教程,但在模型打印的所有不同方法中,我都无法理解为什么有很多方法可以打印.
这两种方法有什么区别:
<td>
@item.Name
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
Run Code Online (Sandbox Code Playgroud)
哪一个更好?
如果您有任何给定数据类型的自定义显示模板,则使用@Html.DisplayFor()将尊重该自定义显示模板并按您的意愿呈现代码.
@Model.YourField直接使用只需调用.ToString()该字段并输出该调用返回的内容.
试试这个:
Models/IndexModel.cs:
public class IndexModel
{
public DateTime HireDate { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
Controller/HomeController.cs:
public ActionResult Index()
{
IndexModel model = new IndexModel {HireDate = new DateTime(2015, 8, 15)};
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
Views/Home/Index.cshtml:
<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>
Run Code Online (Sandbox Code Playgroud)
最后是自定义显示模板:
Views/DisplayTemplates/DateTime.cshtml:
@{
<span class="datetime">@Model.ToString("MMM dd, yyyy / HH:mm")</span>
}
Run Code Online (Sandbox Code Playgroud)
您的输出现在将是:
Output directly: 15.08.2015 00:00:00 // Output from Model.HireDate.ToString();
Output via DisplayFor: Aug 15, 2015 . 00:00 // Output as defined in your custom display template
Run Code Online (Sandbox Code Playgroud)
哪一个更好现在真的取决于你想做什么:
通常,我更喜欢使用@Html.DisplayFor(),因为通常,如果我经历了定义自定义显示模板的麻烦,我可能也想使用它
但如果您只需要"原始"输出,而无需自定义渲染,您也可以@model.YourField直接使用
所以这真的是你想要/需要的问题 - 选择最适合你需求/要求的那个!
| 归档时间: |
|
| 查看次数: |
233 次 |
| 最近记录: |