Using Jquery Globalize with MVC 5 - javascript

I am trying to use the MVC unobstrusive validation with jquery globalize plugin in MVC5 (in conjunction with the package jquery-validate-globalize). For learning purposes I started a demo project as per here, but it fails to run with globalize (it works on default Microsoft unobstrusive validation). The model is very simple:
public class GlobalizeModel
{
[Range(10.5D, 20.3D)]
public decimal Double { get; set; }
[Required]
public DateTime? DateTime { get; set; }
}
I try to initiate Globalize as follows at the bottom of the _Layout page (the view is minimal with 2 input only): (I get list of necessary files from https://johnnyreilly.github.io/globalize-so-what-cha-want/)
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<!--cldr scripts-->
<script src="~/Scripts/cldr.js"></script>
<script src="~/Scripts/cldr/event.js"></script>
<script src="~/Scripts/cldr/supplemental.js"></script>
<!--globalize scripts-->
<script src="~/Scripts/globalize.js"></script>
<script src="~/Scripts/globalize/number.js"></script>
<script src="~/Scripts/globalize/date.js"></script>
<!--jquery globalize-->
<script src="~/Scripts/jquery.validate.globalize.js"></script>
<script>
$.when(
$.getJSON("/Scripts/cldr/supplemental/likelySubtags.json"),
$.getJSON("/Scripts/cldr/main/en/numbers.json"),
$.getJSON("/Scripts/cldr/supplemental/numberingSystems.json"),
$.getJSON("/Scripts/cldr/main/en/ca-gregorian.json"),
$.getJSON("/Scripts/cldr/main/en/timeZoneNames.json"),
$.getJSON("/Scripts/cldr/supplemental/timeData.json"),
$.getJSON("/Scripts/cldr/supplemental/weekData.json"),
$.getJSON("/Scripts/cldr/main/tr/numbers.json"),
$.getJSON("/Scripts/cldr/main/tr/ca-gregorian.json"),
$.getJSON("/Scripts/cldr/main/tr/timeZoneNames.json"),
console.log("JSONs loaded")
).then(function () {
console.log("start slicing");
return [].slice.apply(arguments, [0]).map(function (result) {
console.log("slicing done");
return result[0];
});
}).then(Globalize.load).then(function () {
Globalize.locale("en");
console.log("Locale set to en");
}).then(console.log("LOADED EVERYTHING"));
</script>
But when I run the page, I only see the console logs JSOns loaded and LOADED EVERYTHING. Moreover, when I try a client side validation by typing anything in the number textbox (and of course when the focus is lost), I get the following error in the console:
Uncaught Error: E_DEFAULT_LOCALE_NOT_DEFINED: Default locale has not been defined.
This post here is similar, and I tried to check the things listed there. I think my JSON objects are not fetched, but I am not good aj JS so I am not sure on that. I added the following items to web.config to see if this is something related with file serving, with no avail:
<system.webServer>
<staticContent>
<remove fileExtension=".json"/>
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
</system.webServer>
The culture is set to auto in web.config as follows:
<system.web>
<globalization culture="auto" uiCulture="auto" />
<compilation debug="true" targetFramework="4.5.2"/>
<httpRuntime targetFramework="4.5.2"/>
</system.web>
You can see Scripts folder structure in here:
So, what is the problem here? How can I make this thing work?

I recently ran into the same problem, trying to add I18n to an MVC5 web app. After several days of research and partly using your code as base, I found some things that helped me implement it.
My Solution:
In a separate project, I added decimal and DateTime properties to the ApplicationUser class:
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
public DateTime birthdate { get; set; }
public decimal balance { get; set; }
}
I also modified the RegisterViewModel to accept those properties, as follows:
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Required]
[DataType(DataType.DateTime)]
public DateTime birthdate { get; set; }
[Required]
[DataType(DataType.Currency)]
public decimal balance { get; set; }
}
Then, I set the culture in a base controller, from which other controllers inherit:
public class BaseController : Controller
{
protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
{
string[] cultures = { "es-CL", "es-GT", "en-US" };
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cultures[1]);
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
return base.BeginExecuteCore(callback, state);
}
}
That's just for testing purposes, not the way I fetch culture in the real app.
My file structure is the same as yours and I didn't modify the web.config file.
I also used this link for dependencies. But then I modified a few things in the scripts section of Register.cshtml:
<!-- CLDR -->
<script src="~/Scripts/cldr.js"></script>
<script src="~/Scripts/cldr/event.js"></script>
<script src="~/Scripts/cldr/supplemental.js"></script>
<!-- Globalize -->
<script src="~/Scripts/globalize.js"></script>
<script src="~/Scripts/globalize/number.js"></script>
<script src="~/Scripts/globalize/date.js"></script>
<!-- $ validate -->
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.globalize.js"></script>
<!-- fetch files -->
<script>
$.when(
$.getJSON("/Scripts/cldr/supplemental/likelySubtags.json"),
$.getJSON("/Scripts/cldr/main/en/numbers.json"),
$.getJSON("/Scripts/cldr/supplemental/numberingSystems.json"),
$.getJSON("/Scripts/cldr/main/en/ca-gregorian.json"),
$.getJSON("/Scripts/cldr/main/en/timeZoneNames.json"),
$.getJSON("/Scripts/cldr/supplemental/timeData.json"),
$.getJSON("/Scripts/cldr/supplemental/weekData.json"),
$.getJSON("/Scripts/cldr/main/tr/numbers.json"),
$.getJSON("/Scripts/cldr/main/tr/ca-gregorian.json"),
$.getJSON("/Scripts/cldr/main/tr/timeZoneNames.json"),
).then(function () {
console.log("start slicing");
return [].slice.apply(arguments, [0]).map(function (result) {
console.log("slicing done");
return result[0];
});
}).then(Globalize.load).then(function () {
Globalize.locale("en");
console.log("Locale set to en");
}).then(console.log("LOADED EVERYTHING"));
</script>
The _Layout view scripts weren't modified at all, and I had no problem with the console logs.
That's all, it worked out for me, and as it's a very similar case, I hope it works for you too.

Related

Directing user to another page in ASP.Net MVC application leads to syntax error in auto-generated code

Snippet from my _layout.cshtml file
<body>
<!--
NAVBAR
-->
<div class="navBar">
<input id="homeButton" type="submit" name="homeButton" value="Home"/>
<input id="toolsButton" type="submit" name="toolsButton" value="Tools"/>
<input id="contactButton" type="submit" name="contactButton" value="Contact Me"/>
<input id="supportButton" type="submit" name="supportButton" value="Support"/>
<input id="aboutButton" type="submit" name="aboutButton" value="About"/>
</div><!--TODO: STYLE THESE -->
<script>
const homeButton = document.getElementById("homeButton");
const toolsButton = document.getElementById("toolsButton");
const contactButton = document.getElementById("contactButton");
const supportButton = document.getElementById("supportButton");
const aboutButton = document.getElementById("aboutButton");
homeButton.addEventListener("click", () => {
window.location.href = "/";
});
toolsButton.addEventListener("click", () => {
window.location.href = "/Tools/Index"; // "/Tools" doesn't work either
});
contactButton.addEventListener("click", () => {
window.location.href = "/";
});
supportButton.addEventListener("click", () => {
window.location.href = "/";
});
aboutButton.addEventListener("click", () => {
window.location.href = "/";
});
</script>
The error generated when button clicked
Server Error in '/' Application.
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS1003: Syntax error, '>' expected
Source Error:
Line 29:
Line 30:
Line 31: public class _Page_Views_Tools_Index_cshtml : System.Web.Mvc.WebViewPage<LgbtqWebsiteNoDb.Models.Tool;> {
Line 32:
Line 33: #line hidden
Source File: c:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\App_Web_index.cshtml.f024d85f.citsmrxd.0.cs Line: 31
Detailed compiler output
C:\Program Files (x86)\IIS Express> "C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe" /t:library /utf8output /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_32\System.Web\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Web.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Data.DataSetExtensions\v4.0_4.0.0.0__b77a5c561934e089\System.Data.DataSetExtensions.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_32\System.Data\v4.0_4.0.0.0__b77a5c561934e089\System.Data.dll" /R:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\assembly\dl3\87f9e4d5\000e9c93_3d27cf01\System.Web.Optimization.dll" /R:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\App_global.asax.ewmqttqt.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Web.Extensions\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.Extensions.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Activities\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Activities.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Web.Services\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Web.Services.dll" /R:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\assembly\dl3\b5be25e0\003c87e2_1a87d401\System.Web.WebPages.Razor.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Web.ApplicationServices\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.ApplicationServices.dll" /R:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\assembly\dl3\77f8a528\001bc110_4318cf01\WebGrease.dll" /R:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\assembly\dl3\7a6f1e22\0016534c_1a87d401\System.Web.Razor.dll" /R:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\assembly\dl3\0bd5514f\8682d14f_c649d701\LgbtqWebsiteNoDb.dll" /R:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\assembly\dl3\5eada7ec\003c87e2_1a87d401\System.Web.WebPages.dll" /R:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\assembly\dl3\bfe09c51\003c87e2_1a87d401\System.Web.Helpers.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Runtime.Serialization\v4.0_4.0.0.0__b77a5c561934e089\System.Runtime.Serialization.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Core\v4.0_4.0.0.0__b77a5c561934e089\System.Core.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\Microsoft.VisualStudio.Web.PageInspector.Loader\v4.0_1.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.Web.PageInspector.Loader.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel\v4.0_4.0.0.0__b77a5c561934e089\System.ServiceModel.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Activation\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Activation.dll" /R:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\assembly\dl3\0103d10e\00c8d184_3aaece01\Antlr3.Runtime.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Web\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Web.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Drawing\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Drawing.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_32\System.EnterpriseServices\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.EnterpriseServices.dll" /R:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\assembly\dl3\39611dac\001cbe16_536acd01\Microsoft.Web.Infrastructure.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.ComponentModel.DataAnnotations\v4.0_4.0.0.0__31bf3856ad364e35\System.ComponentModel.DataAnnotations.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.WorkflowServices\v4.0_4.0.0.0__31bf3856ad364e35\System.WorkflowServices.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.IdentityModel\v4.0_4.0.0.0__b77a5c561934e089\System.IdentityModel.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Activities\v4.0_4.0.0.0__31bf3856ad364e35\System.Activities.dll" /R:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\assembly\dl3\129223b9\003c87e2_1a87d401\System.Web.WebPages.Deployment.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Xml.Linq\v4.0_4.0.0.0__b77a5c561934e089\System.Xml.Linq.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Xml\v4.0_4.0.0.0__b77a5c561934e089\System.Xml.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\Microsoft.CSharp\v4.0_4.0.0.0__b03f5f7f11d50a3a\Microsoft.CSharp.dll" /R:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\assembly\dl3\b4261359\00cdd33c_1a87d401\System.Web.Mvc.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Web.DynamicData\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.DynamicData.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll" /R:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\assembly\dl3\dd04c433\00eff220_9da8d301\Newtonsoft.Json.dll" /out:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\App_Web_index.cshtml.f024d85f.citsmrxd.dll" /D:DEBUG /debug+ /optimize- /w:4 /nowarn:1659;1699;1701;612;618 /warnaserror- "C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\App_Web_index.cshtml.f024d85f.citsmrxd.0.cs" "C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\App_Web_index.cshtml.f024d85f.citsmrxd.1.cs"
Microsoft (R) Visual C# Compiler version 4.8.4084.0
for C# 5
Copyright (C) Microsoft Corporation. All rights reserved.
This compiler is provided as part of the Microsoft (R) .NET Framework, but only supports language versions up to C# 5, which is no longer the latest version. For compilers that support newer versions of the C# programming language, see http://go.microsoft.com/fwlink/?LinkID=533240
c:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\App_Web_index.cshtml.f024d85f.citsmrxd.0.cs(31,106): error CS1003: Syntax error, '>' expected
c:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\App_Web_index.cshtml.f024d85f.citsmrxd.0.cs(31,106): error CS1519: Invalid token ';' in class, struct, or interface member declaration
I have tried to redirect the users to other pages via Razor with Response.Redirect("/Tools"); but this doesn't work either, throwing a different exception on the same line (compiler just picked a different character to throw on).
My Tools controller
using System.Collections.Generic;
using System.Web.Mvc;
using LgbtqWebsiteNoDb.Models;
using static LgbtqWebsiteNoDb.Models.Tool;
using Microsoft.Ajax.Utilities;
namespace LgbtqWebsiteNoDb.Controllers
{
public class ToolsController : Controller
{
private static readonly List<Tool> Tools = new List<Tool>()
{
new Tool
{
ToolName = "Hateful Countries Finder",
ReleaseDate = DateTime.Now.Date,
UpdateDate = DateTime.Now.Date, //GetLastUpdate(toolId:1), //TODO: Fix this method, it looks for the file in the wrong place
ToolId = 1,
ToolDesc = "A tool to find out which countries in the world have anti-Lgbtq+ laws which apply to you",
ToolThumbUrl = "",
ToolThumbAlt = ""
},
new Tool
{
ToolName = "Hateful Map",
ReleaseDate = DateTime.Now.Date,
UpdateDate = DateTime.Now.Date, //GetLastUpdate(toolId:2),
ToolId = 2,
ToolDesc = "A tool to show how many world countries have generic anti-Lgbtq laws",
ToolThumbUrl = "",
ToolThumbAlt = ""
}
};
public static int ToolCount = Tools.Count;
// GET: Tools/
public ActionResult Index()
{
ViewBag.Title = "Tools | Home";
return View();
}
// GET: Tools/HatefulCountriesFinder
public ActionResult HatefulCountriesFinder()
{
ViewBag.Title = "Tools | Hateful Countries";
return View();
}
// GET: Tools/HatefulMap
public ActionResult HatefulMap()
{
ViewBag.Title = "Tools | Hateful Map";
return View();
}
}
}
Tools model
public class Tool
{
/// <summary>
/// Getter and Setter for the name of a given tool
/// </summary>
public string ToolName { get; set; }
/// <summary>
/// Getter and Setter for the date the tool was released
/// </summary>
[DataType(DataType.Date)] public DateTime ReleaseDate { get; set; }
/// <summary>
/// Getter and Setter for the date the tool was last updated
/// </summary>
[DataType(DataType.Date)] public DateTime UpdateDate { get; set; }
/// <summary>
/// Getter and Setter for the tool ID
/// </summary>
public int ToolId { get; set; }
/// <summary>
/// Getter and Setter for the description of the tool
/// </summary>
public string ToolDesc { get; set; }
/// <summary>
/// Getter and Setter for the thumbnail of the tool image
/// </summary>
public string ToolThumbUrl { get; set; }
/// <summary>
/// Getter and Setter for the alt text of the thumbnail
/// </summary>
public string ToolThumbAlt { get; set; }
/// <summary>
/// Getter and Setter for the number of tools; used for enumeration
/// </summary>
public int ToolCount { get; set; }
/// <summary>
/// A method to update the tool, and change the last updated date
/// </summary>
/// <returns>DateTime</returns>
public static DateTime UpdateTool()
{
//TODO: Write the actual code for this
//TODO: Write new update DateTime to the appropriate file; See GetLastUpdate() for more
return DateTime.Now.Date;
}
}
}
Tools/Index.cshtml
#model LgbtqWebsiteNoDb.Models.Tool;
<!DOCTYPE html>
<html lang="en-GB">
<head>
<title>#ViewBag.Title</title>
<!-- Removed the bulk of the head -->
</head>
<body>
<div class="title">
</div>
<table>
#for (var i = 0; i < #Model.ToolCount; i++)
{
<tr>
<td>
<div class="toolTitle">
#Model.ToolName;
</div>
<div class="toolThumb">
<img src=#Model.ToolThumbUrl alt=#Model.ToolThumbAlt>
</div>
<div class="toolDesc">
#Model.ToolDesc;
</div>
</td>
</tr>
}
</table>
</body>
</html>
I am using .Net v4.7.2 (I would be using 5.0.0 but none of my IDEs seem to want to use the newest version, I'm on a time crunch so can't spend ages debugging that so I'm just making do)
Cheers
I'm not entirely sure but the ; at the end of the line:
#model LgbtqWebsiteNoDb.Models.Tool;
in Tools/Index.cshtml might be messing it up
to me you missed Syntax error, '>' expected for img tag in file Tools/Index.cshtml

Calling applet's method from JavaScript

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");

Using jquery to set asp.net mvc model values

I have a gap in my understanding. I have two view screens, one successfully gets a value from a devexpress selection grid but one doesn't... and I don't understand what I am doing differently.
When I use firebug I can't find where the model is set in the DOM.
The following works:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel.DataAnnotations;
namespace EtracsWeb.Areas.IO.Models
{
public class VoyageInputModel
{
[Required(ErrorMessage = "Value must be supplied")]
[Display(Name = "Show Received Voyages")]
public bool ShowReceivedVoyages { get; set; }
public string VoyageIDS { get; set; }
}
}
being used in the view (which works)...here is a fragment of the view:
#using EtracsWeb.Areas.IO.Models;
#model VoyageInputModel
#{
ViewBag.Title = "Voyage (Receive/UnReceive/etc..)";
Layout = "~/Views/Shared/_LayoutMenu.cshtml";
}
#* MUST go here and NOT at end or code won't work *#
<script type="text/javascript">
//This is the value from the devExpress Selection Grid...
function OnSelectionChanged(s, e) {
s.GetSelectedFieldValues("VoyageID", GetSelectedFieldValuesCallback);
}
//This is the value from the InputModel...notice it is different...
//This is why we need this two step process.
function GetSelectedFieldValuesCallback(values) {
// voyage_ids = values;
//alert(values);
document.getElementById('VoyageIDS').value = values;
//alert(document.getElementById('VoyageIDS').value)
}
</script>
Notice I am getting the value from the OnSelection changed as one variable and setting in the inputModel as different name....this all works...
I am trying to do it with a second view and the code dies where I try to access the variable in the model using a getElementbyID .... originally I was trying to use an int...but I switched it to a string...but neither work....
Where in the heck is the model in the DOM? How can I use Firebug to view the #model values (from asp.net mvc)???
Any ideas where I went wrong on the second window?
Here is the second inputmodel:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel.DataAnnotations;
namespace EtracsWeb.Areas.Vehicle.Models
{
public class BookMarkListInputModel
{
public string SelectedBookMarkID { get; set; }
public int BookMarkID { get; set; }
public IEnumerable<BookMark> BookMarks { get; set; }
}
}
and the second view fragment:
#using EtracsWeb.Areas.Vehicle.Models
#model BookMarkListInputModel
#{
ViewBag.Title = "List";
Layout = "~/Views/Shared/_LayoutMenu.cshtml";
}
#* MUST go here and NOT at end or code won't work *#
<script type="text/javascript">
//This is the value used in the DevExpress Selection Grid
function OnSelectionChanged(s, e) {
s.GetSelectedFieldValues("BookMarkID", GetSelectedFieldValuesCallback);
}
//This is the variable from the InputModel...notice it can be different
//So we need to have this two step process.
function GetSelectedFieldValuesCallback(values) {
alert(values);
document.getElementById('SelectedBookMarkID').value = values;
alert(document.getElementById('SelectedBookMarkID').value)
}
function Success(data) {
// alert(data.ReturnMessage);
id1.innerHTML = data.ReturnMessage;
}
</script>

JavascriptResult puts javascript to the page as a string?

Iam a newbie of .NET MVC. I was trying to run all return types of MVC but I couldnt do work javascriptResult. The below is in my controller:
public ActionResult DoSomething() {
string s = "alert('Hello world!');";
return JavaScript(s);
}
This is in my view
#Ajax.ActionLink("click", "DoSomething", new AjaxOptions())
When I clicked the link, it puts "alert('Hello world!');" as a string and so not firing the alert. Whats wrong here ?
Seems that the documentation is "wrong" and the Controller.JavaScript action result is most likely only considered to return JavaScript include files (see also this thread):
Controller
public ActionResult JavaScript()
{
string s = "alert('Hello world!');";
return JavaScript(s);
}
View
<script type="text/javascript" src="~/Controller/JavaScript"></script>
If you want to return inline JavaScript you can use Controller.Content as your action result in combination with Html.RenderAction:
Controller
public ActionResult JavaScript()
{
string s = "alert('Hello world!');";
return Content(s);
}
View
<script type="text/javascript">
#{ Html.RenderAction("JavaScript", "Controller"); }
</script>

Display HTML and XML content on the same HTML page

I have a HTML page in which I have a button; pressing that button a javascript function is called - here results a String which is the representation of an xml. I want to represent this xml on the same page with the button, similar with what is in the picture below:!
Here is the simplified code I've tried but did not worked (see under the code the result of it - nothing displayed):
<html>
<head>
<script type="text/javascript">
function xml_test()
{
var xmlString = "<note><name>Kundan Kumar Sinha</name><place>Bangalore</place><state>Karnataka</state></note>";
var my_div = document.getElementById("labelId");
alert(xmlString)
my_div.innerHTML += xmlString;
}
</script>
</head>
<body>
<input type="button" value="TEST" onclick="xml_test()"/>
<br><br>
<label id="labelId">XML: </label>
</body>
</html>
I've tried with an iframe also, but I do not have an file for the src attribute.
What I've tried is:
<html>
<head>
<script type="text/javascript">
function populateIframe() {
var xml = "<?xml version='1.0' encoding='UTF8' standalone='yes'?><note><name>Kundan Kumar Sinha</name><place>Bangalore</place><state>Karnataka</state></note>";
var iframe = document.getElementById('myIframe');
var idoc= iframe.contentDocument || iframe.contentWindow.document; // IE compat
idoc.open("text/xml"); // I know idoc.open(); exists but about idoc.open("text/xml"); I'm not sure if exists;
idoc.write('<textarea name="xml" rows="5" cols="60"></textarea>');
//idoc.write(xml); // doesn't work
idoc.getElementsByTagName('textarea')[0].value= xml;
idoc.close();
}
</script>
</head>
<body onload="populateIframe();">
<iframe id="myIframe" width="900" height="400"></iframe>
</body>
</html>
and the result is:
I've already looked over How to display XML in a HTML page as a collapsible and expandable tree using Javascript?
I took some ideas from here
Thank you for helping me!
Just Create am HttpHandler, and open it in a Iframe:
public class Handler : IHttpHandler
{
#region IHttpHandler Members
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
XmlSerializer serializer = new XmlSerializer(typeof(Note));
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream, Encoding.Unicode);
serializer.Serialize(writer, new Note() { Name = "Kundan Sinha", Place = "Bangalore", State = "Karnataka" });
int count = (int)stream.Length;
byte[] arr = new byte[count];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(arr, 0, count);
UnicodeEncoding utf = new UnicodeEncoding();
stream.Close();
writer.Close();
context.Response.ContentType = "text/xml;charset=utf-8";
context.Response.Write(utf.GetString(arr).Trim());
context.Response.Flush();
}
#endregion
}
public class Note
{
public string Name { get; set; }
public string Place { get; set; }
public string State { get; set; }
}
You can pass your received xml string to this where I am doing
context.Response.Write('Pass you XML data here');
You must use your favorite JavaScript library with a tree widget to display that XML in tree form.
Note that the "tree-like" view you see is actually IE's default view for XML files. Other browsers will have different views for XML files, and some do not even let you view XML files without a plug-in.
You should not depend on browser-specific functionality if viewing the XML in tree form is important to your page's functionality.
If you, however, just want to press a button and then the whole page gets turned into an XML, then by all means just redirect to that XML URI on button press. IE will show that XML file in tree form, while other browsers may either ask you to download the file, or display the XML file in whatever format that is determined by their plugin's.
I set the xml data in the src attribute:
iframeElement.setAttribute('src', 'data:text/xml,<test>data</test>');

Categories

Resources