Search code examples
c#htmllocalizationasp.net-core-tag-helpers

using localization with label tag helper


Ttextinput.cshtml

@inject Microsoft.AspNetCore.Mvc.Localization.IViewLocalizer localizer
@model string
<div class="form-group col-sm-6" >
  <label asp-for=@(localizer[@Model]) class=" control-label form-label "></label>
  <div class="">
    <input asp-for="@Model" class="form-control form-textbox"/>
    <span asp-validation-for="@Model" class="text-danger "></span>
  </div>
</div>


"workflowformpage.cshtml"
using REU.ViewModelContracts
@model IWorkflowViewModel
<fieldset class=" form-group form">

        @if (Model.GetType().BaseType == typeof(AssignResultCollectionViewModel))
        {

            @Html.Partial("AssignResultCollection", Model);

        }
        else
        {
            foreach (var propertyInfo in Model.GetDisplayPropertyInfos())
            {
                @Html.Editor(propertyInfo.Name, null, Model.GetQualifiedPropertyName(propertyInfo.Name))
                //break;
            }
        }


    </fieldset>

I have a view displaying a form. And labels of textbox comes from model for which I used " "and it works well and gives the value but now I want to implement localization with label, I tried something like this

<label asp-for="@localizer[@Model]" class=" control-label form-label ">

which doesn't give me values. Can anyone suggest how to solve this?

<label asp-for="@localizer[@Model]" class=" control-label form-label "> 
</label>

Solution

  • The asp-for attribute is meant to contain the name of a C# property present in your page's model, and is not meant to contain a string to be displayed.

    For example :

    public class MyPageModel
    {
        public string Email {get;set;}
    }
    

    View:

    @model MyPageModel
    <label asp-for="Email"></label>
    

    This will display the content of the MyPageModel.Email property that you pass in your controller. Therefore, it doesn't really make sense to pass a localized string in asp-for.

    To complete your example, I'll assume that your @Model variable is a string. You could use this:

    @using Microsoft.AspNetCore.Mvc.Localization
    @inject IViewLocalizer Localizer
    <label>@Localizer[@Model]</label>