how to do Localization for one of the @Model prope

2019-08-30 00:04发布

问题:

I have started working on an MVC project and I came accross some scenarios where I feel I am stuck. I need to convert the exisiting MVC3 site to work for multiple language. As I am new, I may use wrong words/definations/keywords for MVC3 while explaing so please bare with me.

I have one HeaderPage.cshtml and it has a view model binded to it by

@model IHeaderPage

And it ouputs a property of this model:

<h3>@Model.HeaderName</h3>

I called this view from MainPage.cshtml

@Html.Partial("HeaderPage")

Now in the Controller's Action method I change the model's property

objHeaderPage.HeaderName="Fill your Registeration details";

And when i run the project i see the the text "Fill your Registeration details".

Now how can I change the text value, i.e. it should read from my resx file. I have already created resx files in App_LocalResources folder. I heard that, it can be done by Display Attribute.. but how do i do that or is there any other better way?

回答1:

This should answer your question regarding the use of DisplayAttribute.

I use DisplayAttribute for every property of my ViewModel, but if you have to handle custom messages like "The record can not be saved because of an error...", or something similar, you can simply use

 objHeaderPage.HeaderName = Resources.ResourceMessageName; 

The framework will choose automatically the correct culture. I prefer to put all my resources in a separate projects so I can deploy only the dll of the resources in case of need, but you can also think to deploy the resx files to edit them directly on the production machine. I guess it's up to what you prefer/need.



回答2:

use System.ComponentModel.DataAnnotations Namespace in ViewModel.

[Display(Name="Fill your Registeration details")]
public string HeaderName{get;set;}

also you can use your resource file. Just review http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx