Change display name of foreign key MVC

asp.net-mvc asp.net-mvc-5 c# entity-framework-6

Question

In my MVC app I have one model which is of a certain 'category', another model.
When the index view is displayed both the name of this model and the category name are called 'Name', how do i change the displayed name of the category to something other than name?

[Table("Product")]
    public partial class Product
    {
        public int ProductId { get; set; }

        [Required]
        public string Name { get; set; }

        [Required]
        public string Description { get; set; }

        public int CategoryId { get; set; }

        public decimal Price { get; set; }

        public virtual Category Category { get; set; }
    }

I have tried using [DisplayName ("New Name")] above both CategoryId and Category and this doesn't seem to work, can anyone advise me?

Thanks

1
1
10/17/2014 11:56:05 PM

Popular Answer

This can happen when you use scaffolding to generate your views. It happens where drop-down lists are used to select foreign keys. Unlike other generated labels, these labels are passed an additional parameter "labelText" which overrides the DisplayName you set in the model attributes. Remove the additional parameter or change it to the text you want to display. I added the text (ChangeOrRemoveMe) in the sample code below.

    <div class="form-group">
        @Html.LabelFor(model => model.CategoryID, "CategoryID(ChangeOrRemoveMe)", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("CategoryID", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.CategoryID, "", new { @class = "text-danger" })
        </div>
    </div>
2
8/10/2017 5:14:47 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow