1

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

Virus7711
  • 27
  • 1
  • 5
  • Are you using any additional mapping files? – Jesan Fafon Oct 18 '14 at 00:02
  • Not clear what you want but if you use [Display(Name="New Name")]public int CategoryId { get; set; }` and in the view `@Html.LabelFor(m => m.CategoryID)` It will render _"New Name"_ –  Oct 18 '14 at 00:05

1 Answers1

2

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>
codeMethod
  • 46
  • 3