我的雇主已经委托我建立一个非常简单的客户满意度调查。唯一的问题是它必须以英语和西班牙语提供。并且,处理该语言不涉及任何数据库。换句话说,实际的单词必须作为变量存储在代码中。为简单起见(为了讨论的目的),我们只需说明我们需要用英语或西班牙语显示单个句子,具体取决于URL末尾的参数。
鉴于这两句话:
"在屏幕上显示这句话。"
和
" Mostrar la frase en la pantalla。"
我需要一些帮助来完成模型,视图和控制器。你将如何,如何将这两个句子存储在变量中?请记住,最终会有很多句子,所以解决方案需要扩展。
路由:
routes.MapRoute(
"PatientSatisfactionSurvey",
"PatientSatisfactionSurvey/{*LanguageCode}",
new { controller = "Forms", action = "PatientSatisfactionSurvey" },
namespaces: new[] { "xxx.Controllers" }
);
型号:
namespace GEDC.Models
{
public class PatientSatisfactionSurveyPage : Page
{
public List<string> LanguageOptions { get; set; }
public string LanguageCode { get; set; }
public PatientSatisfactionSurveyPage() { }
}
}
控制器:
[HttpGet]
public ActionResult PatientSatisfactionSurvey(string LangCode)
{
PatientSatisfactionSurveyPage pss = new PatientSatisfactionSurveyPage();
// Create list of available language options
pss.LanguageOptions = new List<string> { "English", "Espanol" };
// Check the incoming Language Code (LanCode) against the list off approved options
if (!string.IsNullOrEmpty(LangCode))
{
if (pss.LanguageOptions.Contains(LangCode))
{
pss.LanguageCode = LangCode;
}
else
{
// if the LanCode is not found, default to English
pss.LanguageCode = pss.LanguageOptions.First();
}
}
else
{
// if the LanCode is not provided, default to English
pss.LanguageCode = pss.LanguageOptions.First();
}
}
查看:
我想在这里将逻辑保持在绝对最小值。如同,没有。那么,在某个地方(在控制器中,我假设?)Model.Sentence或一些这样的变量将使用正确的版本填充,具体取决于URL中的参数。
@Model.Sentence
提前致谢!!
答案 0 :(得分:1)
您可以使用我在博客上described in this guide的ResourceFiles + LocalizationRoute + LocalizationAttribute GlobalFilter方法轻松地执行您想要的操作。
本地化路线:
routes.MapRoute(
name: "DefaultLocalized",
url: "{lang}/{controller}/{action}/{id}",
constraints: new { lang = @"(\w{2})|(\w{2}-\w{2})" }, // en or en-US
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
本地化属性:
public class LocalizationAttribute : ActionFilterAttribute
{
private string _DefaultLanguage = "en";
public LocalizationAttribute(string defaultLanguage)
{
_DefaultLanguage = defaultLanguage;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string lang = (string)filterContext.RouteData.Values["lang"] ?? _DefaultLanguage;
if (lang != _DefaultLanguage)
{
try
{
Thread.CurrentThread.CurrentCulture =
Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);
}
catch (Exception e)
{
throw new NotSupportedException(String.Format("ERROR: Invalid language code '{0}'.", lang));
}
}
}
}