I'm working on web-application, it's my first time using asp.net mvc core 2.0. I'm Learning from any tutorials, but everywhere different approaches with model print, I can't understand why there a lot of way for just print.
What is the difference between the two approaches:
<td>
@item.Name
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
And which one is better?
If you have a custom display template for any given data type, using @Html.DisplayFor() will respect that custom display template and render your code as you wished.
Using @Model.YourField directly will just simply call .ToString() on that field and output whatever that call returns.
Try this:
Models/IndexModel.cs:
public class IndexModel
{
public DateTime HireDate { get; set; }
}
Controller/HomeController.cs:
public ActionResult Index()
{
IndexModel model = new IndexModel {HireDate = new DateTime(2015, 8, 15)};
return View(model);
}
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>
And finally the custom display template:
Views/DisplayTemplates/DateTime.cshtml:
@{
<span class="datetime">@Model.ToString("MMM dd, yyyy / HH:mm")</span>
}
Your output will now be:
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
Which one is better now really depends on what you want to do:
typically, I'd prefer to use @Html.DisplayFor(), since normally, if I went through the trouble of defining a custom display template, I probably want to use that, too
but if you just need the "raw" output, without custom rendering, you can always also use @model.YourField directly
So it's really a question of what you want / need - pick the one most suited to your needs / requirements!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With