Can we access Umbraco Dictionary item value from JavaScript ?
As I am using Umbraco 6.0.5
No, you can't do it out-of-the-box.
I had to do this multiple times, and the best way I came up with, is to print all dictionary items as an object when the page loads (in <head> or something). Of curse only items for the current language.
So in your source you have
<script>
var dic = {"quantity":"Quantity","totalPrice":"Total price","securePayment":"Secure payment"};
</script>
And then get is as
window.dic["quantity"]
As far as I know, you can't do it out of the box - haven't actually tried, though.
I would first create a simple rest service in my website that returns the Umbraco dictionary item using a querystring parameter as the alias value
var alias = HttpContext.Current.Request.QueryString["alias"]
if(alias != null)
{
var dictionaryItem = umbraco.GetDictionaryItem(alias)
...
}
Then call your own webservice through javascript to get the value
What I have done is declare variable in using Javascript
<script type="text/javascript">
var UmbracoDicKeyValue = '<%= kraftvaerk.umbraco.Translations.translate("Umbraco_Dic_Key", lang) %>';
</script>
And for setting value of lang variable from server side.
protected string lang = (!String.IsNullOrEmpty(umbraco.library.Session("lang")) ? umbraco.library.Session("lang") : "en-GB");
umbraco.library.setSession("lang", lang);
Now use variable UmbracoDicKeyValue in javascript code.
Related
What is equivalent of MVC5's #Json.Encode method in MVC6? In MVC5 we can access those methods in views. But I can't find any methods which I can access from MVC 6 views.
I don't want to write a helper method if there is already a built in feature in MVC6.
After some search, found it:
#inject IJsonHelper Json;
#Json.Serialize(...)
I've had success with the following:
#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(myObj) as String)
I'm not sure if Json.Encode has made it in yet because it was a part of System.Web which is gone now.
One of the features of #Json.Encode() was automatic HTML encoding of entities within JSON strings, which is helpful to avoid XSS vulnerabilities. The JsonHelper class is based on Json.NET serialization now, which does support at least some (or all) of this same functionality if configured properly. The other solutions here can be vulnerable to XSS attacks if untrusted data is serialized.
Quick example of a vulnerability:
<script>
window.something = #Json.Serialize(new { someprop = "Hello</script><script>alert('xss')</script><script>" });
</script>
Will be rendered as
<script>
window.something = {"someprop":"Hello
</script>
<script>alert('xss')</script>
<script>"};</script>
To properly configure Json.NET to escape HTML entities would be to use the #Json.Serialize(object, serializerSettings) overload and override StringEscapeHandling to EscapeHTML. The settings could be defined in a helper class or injected.
#using Newtonsoft.Json
<script>
#{
var settings = new JsonSerializerSettings {StringEscapeHandling = StringEscapeHandling.EscapeHtml};
}
window.something = #Json.Serialize(new { someprop = "Hello</script><script>alert('xss')</script><script>" }, settings);
</script>
Which is rendered instead as:
<script>
window.something = {"someprop":"Hello\u003c/script\u003e\u003cscript\u003ealert(\u0027xss\u0027)\u003c/script\u003e\u003cscript\u003e"};
</script>
Some other methods of safely serializing data to the page in ASP.NET Core can be found here: https://github.com/aspnet/Docs/blob/master/aspnetcore/security/cross-site-scripting.md
Hi I have a working FilteringSelect which reads from a URL. Entering names will query the database and return the appropriate JSON to populate the filtering select, I can select a value and it stores the ID.
<div data-dojo-type="ComboBoxReadStore" data-dojo-id="assignedUserIdstore"
data-dojo-props="url:'Welcome.do?call=JS&actionRefId=142',
requestMethod:'get'"></div>
<input id='assignedUserId' name='value(assignedUserId)'
data-dojo-type='dijit.form.FilteringSelect'
data-dojo-props="store:assignedUserIdstore, pageSize:5, labelAttr:
'label',queryExpr: '*${0}*', autoComplete: false" />
The issue comes with setting the default value. I have this
<script type='text/javascript'>dojo.ready(function(
{dijit.byId('assignedUserId').setValue('25');});
</script>
This appears to work after a fashion - it does call the server and the server returns this
{ "id":"25", "name":"John Smith" "label":"John Smith"}
However it does nothing to actually populate the filtering select with neither a display nor an actual value for the input. I tried to set the value to the name but that had no effect either. Having it return a collection instead of a single item does not help either.
The comboreadstore is defined as
<script type="text/javascript">
require([
"dojo/_base/declare",
"dojox/data/QueryReadStore",
"dojo/parser",
"dijit/form/FilteringSelect"],
function(declare, QueryReadStore){
declare("ComboBoxReadStore", QueryReadStore, {
fetch:function(request) {
// This results in a xhr request to the following URL (in case of GET):
// /url.php?q=<searchString>
request.serverQuery = {q:request.query.name};
return this.inherited("fetch", arguments);
}
});
}
);
</script>
Using dojo.ready doesn't guarantee that the data you're fetching is ready/loaded. It does fire when dojo is ready and all your required assets have been loaded. So i think you're trying to set the FilteringSelect to a value which doesn't exist in the store yet. You could solve this by waiting with setting the value untill the store is ready. How to do that depends on the store you are using which i can't really make up out of your code. I'm not familiar with ComboBoxReadStore. After some googling i found out it might be an extension of dojox.data.QueryReadStore, which is outdated and unfinished. If so i'de suggest you switch to using dojo.store if possible.
Furthermore: The setValue method on dijits is deprecated, you should be using set('key', val).
I am 3 months into learning KnockoutJS and it has been great so far. However, I am facing an issue with binding.
This is the scenario:
I am using MVC with KO.
MVC model is passed down to the view, converted into a knockout object and pushed into the viewModel variable:
var data = ko.mapping.fromJS(#Html.Raw(Json.Encode(Model)));
var viewModel = new HP.ViewModels.CertificationPathViewModel(data);
ko.applyBindings(viewModel);
Within viewModel, I reference the MVC model as self.data:
ViewModels.CertificationPathViewModel = (function (data) {
var self = ViewModels.BaseEntityViewModel.apply(this, [data]);
// some other code
return { Data: self.Data, };
}
ViewModels.BaseEntityViewModel = (function (data) {
var self = this;
self.data = ko.observable(data);
// other code
return { Data: self.data, };
}
On the view, I data-bind like this:
<div id="drpControl" data-bind="CustomDropdown: Data().BusinessUnits.SelectedGroup, optionSettings: { CustomOptions: Data().Units.Groups, CustomOptionsCaption: '-- Select Group --' }"></div>
I try to update the self.data after an ajax call. I return the entire MVC model object and attempt to replace self.data like this :
self.data(updatedModel)
My expectation is that KO will take care of the update and no extra binding is needed. It works great for simple binding (ex. Value: Data().Something) but it doesn't work for complex binding (ex. value: Data().BusinessUnits.SelectedGroup ).
The controls that have complex binding are still bound to the old model, so KO doesn't know what to pass back next time I submit an ajax request.
Is this a limitation of KO, or I am not doing something properly?
Thanks
the ko.mapping plugin changes every property on self.data into an observable. During your update, you need to remap the updated data.
Since you didn't actually post your code, just unformatted snippets I can't help a whole bunch, but you should start by changing this line: self.data(updatedModel) to this:
ko.mapping.fromJS(updatedModel, self.data);
see the Knockout.JS mapping documentation
Protip for stack overflow - include your full code, to the extent that it's possible. Also, if you can, make a jsfiddle that reproduces your problem.
I got a currency exchange script from coinmill. I want to modify it to work nice in my page. I am a newbie in html/javascript programming thats why i am asking help on this one, pls.
<script src="http://coinmill.com/frame.js"></script>
<script>
var currency_round=true;
var currency_decimalSeparator='.';
var currency_thousandsSeparator=',';
var currency_thousandsSeparatorMin=3;
</script>
$199.00 (US) = <script>currency_show_conversion(199.00,"USD","GBP");</script> GBP<br>
<small>Currency data courtesy coinmill.com</small>
This scripts works fine but shows the conversion for the default value in the script. I need to replace the value ($199.00) to a value from a textbox of id "edit_1". Automatically after the user inserts the currency to exchange, the value will show in the page.
Thanks in Advance.
I am Stephen Ostermiller, and I run http://coinmill.com/. You can make this work with the JavaScript currency API from Coinmill:
Put on onchange event on the textarea
Get the value from the text area using this.value
use the currency_convert(value,from,to) method that is available in frame.js to convert it into the currency of your choice
Write the value to where you want it in the page, for example with document.getElementById('results').innerHTML
Putting it all together:
<script src="http://coinmill.com/frame.js"></script>
<script>
var currency_round=true;
var currency_decimalSeparator='.';
var currency_thousandsSeparator=',';
var currency_thousandsSeparatorMin=3;
</script>
<textarea id=edit_1 onchange="document.getElementById('results').innerHTML=currency_convert(this.value,'USD','GBP')"></textarea><br>
Converted into GBP:<div id=results></div>
<p><small>Currency data courtesy coinmill.com</small></p>
Whene I enter "273" into the textarea, I then see "Converted into GBP: 176.32" on the page.
You can test out a live example on jsfiddle: http://jsfiddle.net/wAxnq/
Is there a utility function for escaping JavaScript in ASP.NET MVC views? I often need to init a little snippet of JavaScript using some values from the view; for instance I may have something like:
<script type="text/javascript">
var page = new Page({ currentUser: "<%= Model.UserName %>" });
page.init();
</script>
I would expect something like:
<script type="text/javascript">
var page = new Page({ currentUser: "<%= Html.JavaScriptEscape(Model.UserName) %>" });
page.init();
</script>
I could, of course, write the function myself. But since there are already built-in utilities form HTML encoding, and since one of the selling points of ASP.NET MVC is that the <% %> is the default rendering mode, and since what I'm trying to achieve is quite common, it makes me wonder why I cannot find anything like that already built-in. Is there, for instance, an easy and elegant way to serialize an object to JSON in views?
Or am doing something against ASP.NET MVC principles? When I hit a problem like this, it usually makes it think that either I’m doing something wrong since I assume that the framework designers spent some time thinking about real world scenarios.
In .NET 4, The HttpUtility class has a variety of static encoding methods for various contexts, including a JavaScriptStringEncode method for this particular purpose.
It's often simpler to just use JSON deserialization, though.
In MVC 5 using Razor templates, the following is possible:
<script type="text/javascript">
var page = new Page({ currentUser: #Html.Raw(Json.Encode(Model.UserName)) });
page.init();
</script>
After some time working in ASP.NET MVC, I concluded that (most likely) there is no build-in helper for it. Of course, it's trivial to write your own. Here is it for the sake of completeness:
using System.Web.Mvc;
using System.Web.Script.Serialization;
namespace MyProject.Helpers
{
public static class JsonExtensions
{
public static string Json(this HtmlHelper html, object obj)
{
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
return jsonSerializer.Serialize(obj);
}
}
}
In a view, it can be used as follows:
<script type="text/javascript">
var page = new Page(<%= Html.Json(new { currentUser: Model.UserName } ) %>);
page.init();
</script>
In my case I needed a string not a json object and this is for Asp.Net Core:
#functions{
public Microsoft.AspNetCore.Html.IHtmlContent ToJS(string value)
{
return Html.Raw("'" + value.Replace("'", "\\'").Replace("\r", "\\r").Replace("\n", "\\n") + "'");
}
public Microsoft.AspNetCore.Html.IHtmlContent ToJS(int value)
{
return Html.Raw("" + value);
}
}
This will escape the ' and end of line characters. Also it leaves numbers (int) as a number. This could be overloaded to include float, decimal, etc. as needed.
So, I don't have to think about it or do anything different for each type:
var serverName = #ToJS(m.ServerName);
var appSiteUrl = #ToJS(m.SiteUrl);
var facebookId = #ToJS(m.FacebookAppId);