Editor Template LabelFor - display value rather than name

user1405195 picture user1405195 · Oct 16, 2013 · Viewed 10.1k times · Source

The below correctly renders a label and textbox for each item added to the list instantiated in the controller.

What I need is for the label to display the value of "FavouriteThingID" (i.e 1,2,3,4,5) rather than the literal "FavouriteThingID".

Any ideas?

ViewModel

public class FavouriteThingViewModel
{
    public int FavouriteThingID { get; set; }
    public string FavouriteThingName { get; set; }
}

Editor Template

@model _5fave.Models.FavouriteThingViewModel

<div class="control-group">
    @Html.LabelFor(m => m.FavouriteThingID, new { @class = "control-label" })
    <div class="controls">
        @Html.TextBoxFor(m => m.FavouriteThingName)
        @Html.ValidationMessageFor(m => m.FavouriteThingName, null, new { @class = "help-inline" })
    </div>
</div>

Controller

var favouriteThings = new List<FavouriteThingViewModel>();
    favouriteThings.Add(new FavouriteThingViewModel { FavouriteThingID = 1, FavouriteThingName = "Raindrops on roses" });
    favouriteThings.Add(new FavouriteThingViewModel { FavouriteThingID = 2, FavouriteThingName = "Whiskers on kittens" });
    favouriteThings.Add(new FavouriteThingViewModel { FavouriteThingID = 3, FavouriteThingName = "Bright copper kettles" });
    favouriteThings.Add(new FavouriteThingViewModel { FavouriteThingID = 4, FavouriteThingName = "Warm woolen mittens" });
    favouriteThings.Add(new FavouriteThingViewModel { FavouriteThingID = 5, FavouriteThingName = "Brown paper packages" });

    viewModel.FavouriteThings = favouriteThings;

Answer

Colin Bacon picture Colin Bacon · Oct 16, 2013

Try

@Html.LabelFor(m => m.FavouriteThingName, Model.FavouriteThingID);

As the label is for the textbox for property FavouriteThingName.

Update

From comments below.

If your property is an int convert to string.

@Html.LabelFor(m => m.FavouriteThingName, Model.FavouriteThingID.ToString());