I wanna use appsettings value from web.config file on html page in javascript or jquery. The content from my web.config file is:
<configuration>
<appSettings>
<add key="ServiceURL" value="http://localhost:16917/Service1.svc"></add>
</appSettings>
</configuration>
I have tried with
var serviceUrl='<%=ConfigurationManager.AppSettings["ServiceURL"].ToString() %>'
alert(serviceUrl);
Instead of showing value from webconfig it is showing <%=ConfigurationManager.AppSettings["ServiceURL"].ToString() %> on alert.
Can anybody help me please.
I think you are missing closing tag '>'
<configuration>
<appSettings>
<add key="ServiceURL" value="http://localhost:16917/Service1.svc"> </add>
</appSettings>
</configuration>
1. Change WebConfig UI
<pages pageBaseType="Main.Web.ViewPage">
Create an abstract class that implement from the WebViewPage.
public abstract class ViewPage<T> : WebViewPage<T>
{
public ViewPage()
{
}
public JSSettings UISession
{
get
{
var appSettingsFileBasedSettings = new JSSettings()
{
SessionTimeoutMinutes = ConfigurationManager.AppSettings["SessionTimeoutMinutes"]
};
return appSettingsFileBasedSettings;
}
}
}
In the html page just do something like.
<script type="text/javascript">
var show = {
Settings : #Html.Raw(Json.Encode(this.UISession))
};
console.log(show);
</script>
Hope it help.
This should work:
var test = {
ServiceURL: <%=ConfigurationManager.AppSettings["ServiceURL"] %>
}
You can't do that with static HTML file, at least not in any good way.
Instead, use the power of ASP.NET and work with a Web Form, where you have Code Behind.
In the code behind, send the value from the server to the client as JS variable:
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "ServiceURL_JS",
string.Format("var serviceUrl = \"{0}\"; ",
ConfigurationManager.AppSettings["ServiceURL"]), true
);
}
Now you can access the variable serviceUrl in the client side JS.
Related
I need to print some information via an applet.
My applet from signed qds-client.jar:
public class PrintText extends Applet implements Printable {
private ClientAccount clientAccount;
public ClientAccount getClientAccount() {
return clientAccount;
}
public void setClientAccount (ClientAccount clientAccount) {
this.clientAccount = clientAccount;
}
public void setClientAccountFromJSON(String json) {
this.clientAccount = toClientAccountFromJSON(json);
System.out.println("------------------------------SetClient");
}
public int print(Graphics g, PageFormat format, int page) throws
...
}
public void printText() throws PrinterException {
...
}
private String getTextToPrint(ClientAccount clientAccount) throws PrinterException {
...
}
private ClientAccount toClientAccountFromJSON(String json) {
return JsonUtils.fromJson(ClientAccount.class, json);
}
public void startPrint () {
System.out.println("------------------------------------------Start");
}
}
Accordinng JNLP:
<?xml version="1.0" encoding="utf-8"?>
<jnlp spec="1.5+" codebase="http://localhost:10099/partials/" href="print.jnlp">
<information>
....
</information>
<resources>
<jar href="/partials/qds-client.jar"/>
<jar href="/partials/core-3.2.1.jar"/>
<jar href="/partials/gson-2.3.1.jar"/>
</resources>
<applet-desc name="printText" main-class="com.qdsrest.utils.printer.PrintText" width="500" height="200"></applet-desc>
<update check="background"/>
<security>
<all-permissions/>
</security>
and HTML tag:
<applet name="printApplet" jnlp_href="/partials/print.jnlp" width="10" height="10">
<param name="permissions" value="all-permissions"/>
</applet>
When I call applet's method from js file like this:
document.printApplet.setClientAccountFromJSON({/not empty/});
I get
Error: Error calling method on NPObject!
in Mozilla and
basic: JNLP2ClassLoader.findClass: com.google.gson.internal.bind.CollectionTypeAdapterFactory: try again ..
basic: JNLP2ClassLoader.findClass: com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter: try again ..
basic: JNLP2ClassLoader.findClass: com.google.gson.internal.bind.MapTypeAdapterFactory: try again ..
basic: JNLP2ClassLoader.findClass: com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter: try again ..
basic: JNLP2ClassLoader.findClass: com.google.gson.internal.bind.JsonAdapterAnnotationTypeAdapterFactory: try again ..
in Java Console and method doesn't work. Why I get "try again .."? What does it mean?
Method toClientAccountFromJSON uses GSON lib gson-2.3.1.jar wich perfectly deserialize JSON object into Java object. What wrong things did I do? Tell me, please, a right thinking way.
I don't recall the current details, but long ago at the age of the first browser wars, there once was an attribute mayscript your applet needed in order to talk to javascript.
Oh and parameter needs to be string:
setClientAccountFromJSON("somestring or stringvar");
I am currently trying to create a control in sitecore much like the treeviewex.
But its unclear to me how I would go about including javascripts like sitecore does.
If someone could point me in the right direction I would appreciate that very much, thank you :)
/Robin
You can create your own processor and add it into the renderContentEditor pipeline. You can find info and code in this blog post about Adding custom Javascript and Stylesheets in the Content Editor
Create a new processor class:
public class InjectScripts
{
private const string JavascriptTag = "<script src=\"{0}\"></script>";
private const string StylesheetLinkTag = "<link href=\"{0}\" rel=\"stylesheet\" />";
public void Process(PipelineArgs args)
{
AddControls(JavascriptTag, "CustomContentEditorJavascript");
AddControls(StylesheetLinkTag, "CustomContentEditorStylesheets");
}
private void AddControls(string resourceTag, string configKey)
{
Assert.IsNotNullOrEmpty(configKey, "Content Editor resource config key cannot be null");
string resources = Sitecore.Configuration.Settings.GetSetting(configKey);
if (String.IsNullOrEmpty(resources))
return;
foreach (var resource in resources.Split('|'))
{
Sitecore.Context.Page.Page.Header.Controls.Add((Control)new LiteralControl(resourceTag.FormatWith(resource)));
}
}
}
And then patch in the processor:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<renderContentEditor>
<processor patch:before="*[1]" type="HideDependentFields.SC.Pipelines.RenderContentEditor.InjectScripts, HideDependentFields.Types" />
</renderContentEditor>
</pipelines>
</sitecore>
</configuration>
I'm currently trying to call a JS script in order to export chart from primefaces chart component.
The problem is that the base64str variable seem to be null, and the responsible script for filling this value is not called for some reason :
xhtml code :
<p:chart id="chart" type="line" widgetVar="chart" model="#{cont.lineModel}" style="height:550px;width:1800px">
<p:ajax event="itemSelect" listener="#{cont.itemSelect}" update="growl" />
</p:chart>
<p:commandButton id="exp" value="Export" icon="ui-icon-extlink"
onclick="exportChart();" actionListener="#{cont.submittedBase64Str}"
/>
<h:inputHidden id="b64" value="#{cont.base64Str}" />
<script type="text/javascript">
function exportChart() {
img = chart.exportAsImage();
document.getElementById('hform:b64').value = img.src;
}
</script>
Controller :
public void submittedBase64Str(ActionEvent event){
// You probably want to have a more comprehensive check here.
// In this example I only use a simple check
if(base64Str.split(",").length > 1){
String encoded = base64Str.split(",")[1];
byte[] decoded = org.apache.commons.codec.binary.Base64.decodeBase64(encoded);
// Write to a .png file
try {
RenderedImage renderedImage = ImageIO.read(new ByteArrayInputStream(decoded));
ImageIO.write(renderedImage, "png", new File("D:\\out.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
Thanks
Change your onclick attribute to onstart.
<p:commandButton id="exp" value="Export" icon="ui-icon-extlink"
onstart="exportChart();" actionListener="#{cont.submittedBase64Str}" />
That should call the JS function.
EDIT
Also, you need to define img and chart in your function.
chart object is the PrimeFaces JS widget. You define widgetVar:
<p:chart ... widgetVar="chart"
And then you can get the chart object in your JS code like this:
PF('chart')
You need to use the PF function to get widgets since PrimeFaces 4.0.
As a side note, it's better to make your img variable local instead of global:
var img = chart.exportAsImage();
Now img is defined only in the scope of the function.
I’m having trouble getting JSON results working with Struts 2.2.1.1.
Does anyone have a simple working example that returns a JSON result to a JSP using Struts 2.2.1.1 and is ready to run in Eclipse as a dynamic web project?
Please include the struts.xml, action class and JSP code. Also, note dependencies. Thank you.
Here’s how to create a simple JSON example using the Struts 2 jQuery plugin.
Go to Struts2 jQuery Plugin Showcase
Navigate to Ajax Forms > Buttonset / Checkboxes
Review the code for Buttonset that was populated from AJAX JSON Result. This is code I selected to create a simple example.
Create dynamic web project in Eclipse
Create a Java package and name it test.
Download the Struts 2 jQuery plugin showcase source (struts2-jquery-showcase-x.x.x-sources.jar) and extract the JAR file.
Import Echo.java, JsonSample.java, and ListValue.java into the test package and move the code into the package with quick fix.
Change the class annotation in Echo.java and JsonSample.java to #ParentPackage(value = "test")
In addition to the standard Struts 2 libraries, ensure that the struts2-json-plugin-x.x.x.jar, struts2-jquery-plugin-x.x.x.jar, and struts2-convention-plugin-x.x.x.jar files are in your classpath.
Create a struts.xml file and add the following XML:
<struts>
<constant name="struts.devMode" value="true" />
<constant name="struts.convention.action.packages" value="test" />
<package name="test" extends="json-default” namespace="/">
</package>
</struts>
Create an index.jsp file and insert the following code:
<s:form id="form2" action="echo" theme="xhtml">
<s:url id="remoteurl" action="jsonsample" />
<sj:checkboxlist href="%{remoteurl}" id=“remoteCheckboxlist” name="echo" list="languageList" label="Language" />
<sj:submit targets="formResult" value="AJAX Submit" indicator=“indicator” button="true"/>
</s:form>
Run the example.
Must see : struts2-x.x.x-all.zip /apps/struts2-showcase-2.2.1.war
Struts 2 and JSON example
Struts 2 autocompleter + JSON example
It is very simple to get Json work with struts2.
For this,
you need to add struts-json plugin*(jsonplugin-0.32.jar)* to classpath.
Your struts.xml file should extends json-default
<package name="base" namespace="/" extends="json-default">
Your action result be like this.
<result type="json"><param name="root">jsonData</param></result>
Inside action class, declare json as
private LinkedHashMap<K, V> jsonData new LinkedHashMap<k, V>();
and then add the result list to json like
jsonData.put("result", anyList or object);
Thats all we have to do. Then we can access the result using javascript.
Try this, will help you in Struts 2.0.14 with jsonplugin-0.32.jar.
struts.xml:
<struts>
<package name="example" extends="json-default">
<action name="HelloWorld" class="example.HelloWorld" >
<result type="json" />
</action>
<action name="HelloWorld1" class="example.HelloWorld" >
<result name="success" >example/HelloWorld.jsp</result>
</action>
</package>
</struts>
action class Helloworld.java:
package prabhakar;
import glb.DB;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Prabhakar
*/
public class HelloWorld {
private List<StateMaster> stateList= new ArrayList<StateMaster>();
private List<RegnMaster> regnList= new ArrayList<StateMaster>();
private Integer stateId;
public Integer getStateId()
{
return this.stateId;
}
public void setStateId(Integer stateId)
{
this.stateId=stateId;
}
public List<StateMaster> getStateList() {
return stateList;
}
public void setStateList(List<StateMaster> stateList) {
this.stateList = stateList;
}
public void setRegnList(List<RegnMaster> regnList) {
this.regnList = regnList;
}
public List<RegnMaster> getRegnList() {
return regnList;
}
public String execute() throws Exception {
stateList=DB.getStateData()//
if(stateId !=null)
{
regnList=DB.getRegnByStateId(stateId);
}
//setMessage(getText(MESSAGE));
return "success";
}
/**
* Provide default valuie for Message property.
*/
}
You can directly call HelloWorld.action to view the JSON data or else you can bind the JSON data to a form element below.
JSP page HelloWorld.jsp:
/*
Prabhakar
*/
<%# page contentType="text/html; charset=UTF-8" %>
<%# taglib prefix="s" uri="/struts-tags" %>
<script>
<%#include file="../js/jquery-1.7.1.min.js"%>
</script>
<html>
<!-- JavaScript Plugins -->
<script>
function getLoad(){
var stateId = $('#state').val();
$.getJSON('HelloWorld.action', {'stateId': stateId},
function(data) {
var divisionList = (data.regnList);
var options = $("#regn");
options.find('option')
.remove()
.end();
options.append($("<option />").val("-1").text("--Select--"));
$.each(divisionList, function() {
options.append($("<option />").val(this.regnId).text(this.regnName));
});
}
);}
</script>
<!-- jQuery-UI Dependent Scripts -->
<body>
State List <s:select name="stateId" list="stateList" id="state" listKey="stateId" onchange="getLoad()" listValue="stateName" headerKey="0" headerValue="--select--" />
Regn List <s:select name="regnId" list="regnList" listKey="regnId" id="regn" listValue="regnName" headerKey="0" headerValue="--select--" />
</body>
</html>
Happy coding :)
Is it possible to pass a variable to a linked .js file? I tried this:
<sf:JsFileLink ID="JQueryLoader" runat="server" ScriptType="Custom" FileName="~/Files/Scripts/rotatorLoader.js?timeout=1000" />
But firebug is telling me that timeout is not defined. Here is the code for that .js file:
$(document).ready(function() {
$("#rotator > ul").tabs({ fx: { opacity: "toggle"} }).tabs("rotate", timeout, true);
});
I am using <sf:JsFileLink ... /> tag is because the website I am working in utilizes sitefinity and this tag allows me to load external .js files.
UPDATE:
I was able to 'trick' the include by creating an aspx page that emulates a javascript page:
<%# Page Language="C#" %>
<%
Response.ContentType = "text/javascript";
Response.Clear();
string timeout;
try
{
timeout = Session["timeout"].ToString();
}
catch
{
timeout = "4000";
}
%>
$(document).ready(function() {
$("#rotator > ul").tabs({ fx: { opacity: "toggle"} }).tabs("rotate", <%=timeout %>, true);
});
And on the user control page:
[DefaultProperty("BannerTimeout")]
public partial class Custom_UserControls_TabbedRotator : System.Web.UI.UserControl
{
[Category("Configuration")]
[Description("Sets the rotation timeout, in seconds.")]
[DisplayName("Banner Timeout")]
public int BannerTimeout { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
Session.Add("timeout", (BannerTimeout*1000));
}
}
This achieved what I was looking for, and maybe this method can help someone else out.
try this:
<script>
var myvariable = "foo";
</script>
<script src="/link/to/js.js"></script>
No, you can't pass parameters like that and have the script read them in.
Technically you could grab them from the <script> tag, but that would be a real mess.
Could you just output a script block before you include the file?
<script type="text/javascript"> var timeout = 1000; </script>
<script type="text/javascript">
var imagesPath = "emblematiq/img/";
</script>
<script type="text/javascript" src="emblematiq/niceforms.js"></script>
This will work fine on server
No, but you can pass a the value directly to a function in that file or set a variable value that will be used in the external file.