[Dev tip] Basic load string resource for js



namespace Hydra.Common.Infrastructure.Web.Controllers
{
[RoutePrefix("Resource")]
public class ResourceController : Controller
{
public JsonResult GetResources(string keys)
{
if (string.IsNullOrEmpty(keys))
{
return null;
}

var result = new Dictionary<string, string>();
var keysCollection = keys.Split(',');

foreach (var item in keysCollection)
{
var key = item.Trim();
result.Add(key, HydraResourceProvider.Current.GetString(key));
}

return Json(result, JsonRequestBehavior.AllowGet);
}
}
}

GetString function


public string GetString(string key)
{
// find the localized result only if the key is not null
var result = string.Empty;

if (!string.IsNullOrWhiteSpace(key))
{
result = GetString(CultureHelper.CurrentUICulture.Name, key);

// return the original key if didn't find the localized result
if (string.IsNullOrWhiteSpace(result))
{
result = key;
}
}

return result;
}

 

On MVC view

@Html.Hidden("ResoureURL", Url.Action("GetResources", "Resource", new { keys = "View_Template_Design_Error_BrandAsset" }))

On JS

var resources = {};
var url = $('#ResoureURL').val();
$.getJSON(url, function (data) {
resources = data;
});

alert(resources["View_Template_Design_Error_BrandAsset"]);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s