I have an extension method for getting a string from resource file in asp.net mvc 3
public static string Resource(this HtmlHelper htmlHelper, string expression, params object[] args)
{
string path = ((RazorView)htmlHelper.ViewContext.View).ViewPath;
var fields =
(ResourceExpressionFields)
(new ResourceExpressionBuilder()).ParseExpression(expression, typeof(string), new ExpressionBuilderContext(path));
return (!string.IsNullOrWhiteSpace(fields.ClassKey))
? string.Format((string)htmlHelper.ViewContext.HttpContext.GetGlobalResourceObject(
fields.ClassKey,
fields.ResourceKey,
CultureInfo.CurrentUICulture), args)
: string.Format((string)htmlHelper.ViewContext.HttpContext.GetLocalResourceObject(
path,
fields.ResourceKey,
CultureInfo.CurrentUICulture), args);
}
Here is how I use this method
@Html.LabelFor(m => m.Login, Html.Resource("LoginBoxLoginField"))
But I don’t know how to use it in an action of controller
public ActionResult MyAction()
{
//how to get string from resource file using my extension method?
}
For example
if (!ModelState.IsValid)
ModelState.AddModelError(string.Empty, string.Empty/* should be resource string */);
You cannot use it in the controller because you do not have an instance of HtmlHelper inside the controller. And to create an HtmlHelper instance you need a ViewContext. And you have a view context only inside a view. If you want to use this in a controller you will have to refactor it so that this helper depends only on the HttpContext and not on an HtmlHelper.