Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Displaying object ToString() value in View

$
0
0

I have an ASP .Net Core MVC 1.1 web app. In it, I have a view - Details.cshtml which simply displays a selected record:

@model InspectionsData.Models.House

@{
    ViewData["Title"] = "Details";
}<h2>Details</h2><div><dl class="dl-horizontal">
        @*<dd>
            @Html.DisplayFor(model => model.Id)</dd>*@<dt>
            @Html.DisplayNameFor(model => model.Street1)</dt><dd>
            @Html.DisplayFor(model => model.Street1)</dd><dt>
            @Html.DisplayNameFor(model => model.Street2)</dt><dd>
            @Html.DisplayFor(model => model.Street2)</dd><dt>
            @Html.DisplayNameFor(model => model.Street3)</dt><dd>
            @Html.DisplayFor(model => model.Street3)</dd><dt>
            @Html.DisplayNameFor(model => model.City)</dt><dd>
            @Html.DisplayFor(model => model.City)</dd><dt>
            @Html.DisplayNameFor(model => model.Region)</dt><dd>
            @Html.DisplayFor(model => model.Region)</dd><dt>
            @Html.DisplayNameFor(model => model.Country)</dt><dd>
            @Html.DisplayFor(model => model.Country)</dd><dt>
            @Html.DisplayNameFor(model => model.PropertyType)</dt><dd>
            @Html.DisplayFor(model => model.PropertyType)</dd></dl></div><div><a asp-action="Edit" asp-route-id="@Model.Id">Edit</a> |<a asp-action="Index">Back to List</a></div>

In the above, "PropertyType" is a class that looks like this:

public partial class PropertyType
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        public string PropertyTypeName { get; set; }
        public override string ToString()
        {
            return PropertyTypeName;
        }
    }

As you can see, I am overriding the ToString() method in the hope that the View would execute ToString() when it rendered, and therefore display the value of PropertyType, but it's not doing that. So it's just coming up blank. I tried to do this in my view:

 @Html.DisplayFor(model => model.PropertyType.ToString())

But it didn't like that one bit (Error: InvalidOperationException: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions)

Will I have to add a string field to my PropertyType class and bind the View to that for the property type to be displayed? Or is there perhaps a more elegant solution I'm not aware of?

Thanks...


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>