Javascript function found in Index view, but not other views - javascript

I am using ASP.NET MVC 4 to develop a web application. I have an external javascript file which contains a method initializeLocation(). If I reference the file in the Index view of my Home controller it works fine. But when I try to reference the JS file in another view, and call the method in the body onLoad, then I get the following error:
Uncaught ReferenceError: initializeLocation is not defined
Here is the code of my view:
#{
ViewBag.Title = "Online Users";
}
<html>
<head>
<title>Online Users</title>
</head>
<body onload="initializeLocation()">
<h2>Online Users</h2>
<div id="wrapper">
<div id="upperPanel">
<div>
<ul id="onlineUsers" itemid="#HttpContext.Current.User.Identity.Name">
</ul>
</div>
<div id="friends">
</div>
</div>
<div id="bottomPanel">
<input id="submitLocation" type="submit" value="Share Location" style="margin-left: 10px;" /><br />
</div>
</div>​​​​​​​​​​​​​
<label id="locLabel"></label>
<div id="map" style="width: 100%; height: 600px"></div>
<script>
var Pusher_APP_KEY = 'b5ee1a1486b7f0cec06f';
</script>
<script src="http://js.pusher.com/1.12/pusher.min.js"></script>
<script src="~/Scripts/jquery-1.8.2.js" type="text/javascript"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBsjVTOfgW39medqXn6cmOTfVyyxIX3Nl8&sensor=true"> </script>
<script type="text/javascript">
//postURL is used in locationFinder.js to set the URL of POST requests
//It is declared here to be able to use a separate java file instead of embedding it
var postURL = '#Url.Action("Index", "Home")';
</script>
<script type="text/javascript" src="~/Scripts/locationFinder.js">
</script>
</body>
</html>
And here is my controller code:
namespace LBSPrototype1.Controllers
{
public class HomeController : Controller
{
private static readonly PusherProvider Provider = new PusherProvider
(
ConfigurationManager.AppSettings["pusher_app_id"],
ConfigurationManager.AppSettings["pusher_key"],
ConfigurationManager.AppSettings["pusher_secret"]
);
public ActionResult Index(string latitude, string longitude, string username)
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
//
// GET: /Home/OnlineUsers
[AllowAnonymous]
public ActionResult OnlineUsers()
{
return View();
}
//
// POST: /Home/OnlineUsers
[AllowAnonymous]
[HttpPost]
public ActionResult OnlineUsers(string latitude, string longitude, string username)
{
var now = DateTime.UtcNow;
var request = new ObjectPusherRequest(
"chat_channel",
"message_received",
new
{
lat = latitude,
lon = longitude,
user = username,
timestamp = now.ToShortDateString() + " " + now.ToShortTimeString()
});
Provider.Trigger(request);
return View();
}
}
}
I'm new to MVC and am still getting used to the concept of controllers and such, but can't see why the exact same code should work in one view and not the other.

Instead of
<script src="~/Scripts/jquery-1.8.2.js" type="text/javascript"></script>
<script type="text/javascript" src="~/Scripts/locationFinder.js"></script>
Use
<script src="#Url.Content("~/Scripts/jquery-1.8.2.js")" type="text/javascript"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/locationFinder.js")" ></script>
The problem is the url which is render on the page. use #Url.Content to render a url with its rool path reference. it will render correct url while in routing.

Related

How to Pass data from C# server side to htm through webBrowser control?

I am facing a problem passing string to HTML page through javascript.
I have a window form,
A HTML file, where I have my Javascript and HTML code.
In the function in C# page, I have a string that I need to send to the HTML page through javascript. But I can not pass it. Please advise me.
Thanks
My C# method code below
private void Form1_Load(object sender, EventArgs e)
{
Assembly assembly = Assembly.GetExecutingAssembly();
StreamReader reader = new StreamReader(assembly.GetManifestResourceStream("ProjectName.Maps.html"));
webBrowser1.DocumentText = reader.ReadToEnd();
***//pass getDefaultMap() value (str) to the javascript in Maps.html page.***
}
private string getDefaultMap()
{
string str;
str = (#"Exec SP_Map_Display #Opt=1");
return str ;
}
My HTML page is below
<body>
<script>
$(document).ready(function () {
$("#btnSubmit").click(function () {
***// Get the data from C# code str***
}
</script>
<input type="button" name="btnSubmit" value="Submit" />
<div id="dvMap">
</div>
</body>
Assuming this is WinForms since there's a WebBrowser control, to call C# code from the HTML page JavaScript can be accomplished with this minimum example:
Simple HTML page added to the root of the project and Properties was setup to Copy to Output Directory: Copy if newer this will ensure there's a simple page for testing:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>WebForms WebBrowser Control Client</title>
</head>
<body>
<input type="button" onclick="getLocations()" value="Call C#" />
<script type="text/javascript">
function getLocations() {
var locations = window.external.SendLocations();
alert(locations);
}
</script>
</body>
</html>
The JS function getLocations will call C# method SendLocations, the important parts are the Form1 class annotations and setting webBrowser1.ObjectForScripting = this :
using System.Windows.Forms;
using System.Security.Permissions;
using System.IO;
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.ObjectForScripting = this;
var path = Path.GetFullPath("Client.html");
var uri = new Uri(path);
webBrowser1.Navigate(uri);
}
public string SendLocations()
{
return "SF, LA, NY";
}
}
Clicking the HTML button Call C# will show a popup with the return value from C# method

Section not defined In Index.cshtml in asp.net mvc?

I define the section in Index. cshtml but when I run the application then generate an error section is not defined
I create the same another project, then define the simple method in Index. cshtml then run my application but my current project popup not be displayed??
another project
_layout.cshtml
<div class="container body-content">
#RenderBody()
#RenderSection("simpelmessage")
<footer>
<p>WebApi Crud Oeperation using Entity Framework In Mvc</p>
</footer>
</div>
Index.cshtml
#section simpelmessage{
<h1>simple message</h1>
}
that is work in another project
but my current working project my popup should not be displayed??
I m performing crud operation using api
_layout.cshtml
<div class="container body-content">
#RenderBody()
#RenderSection("alertpopup")
<footer>
<p>WebApi Crud Oeperation using Entity Framework In Mvc</p>
</footer>
</div>
Index.cshtml
#section alertpopup
{
<script src="https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.13.1/alertify.min.js" type="text/javascript">
$(function () {
var successmessage = '#ViewBag.message'
if (successmessage != '')
{
alertify.success(successmessage);
}
});
</script>
}
HomeController.cs
public ActionResult Index()
{
IEnumerable<studentmvcmodel> stdlist;
HttpResponseMessage response = globalvariable.webapiclient.GetAsync("studlogins").Result;
stdlist = response.Content.ReadAsAsync<IEnumerable<studentmvcmodel>>().Result;
ViewBag.message = "record is inserted";
return View(stdlist);
}
public ActionResult create()
{
return View();
}
[HttpPost]
public ActionResult create(studentmvcmodel stud)
{
var username = stud.username;
var passs = stud.password;
if (username != null && passs != null)
{
HttpResponseMessage response = globalvariable.webapiclient.PostAsJsonAsync("studlogins", stud).Result;
ViewBag.message = "data inserted successfully";
return RedirectToAction("Index");
}
else
{
ViewBag.message = "please all the data fillup carefully";
return View("create");
}
}
My record should be created, but I want to popup message when submits the record?? but give the error section is not defined??
What I am trying I went to when I press the submit button, then a popup should be displayed but popup not display?
I hope my question is understood?
I m going to the browser and then ctrl+U then show the popup function.
<script src="https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.13.1/alertify.min.js" type="text/javascript">
$(function popup()
{
var successmessage = 'record is inserted';
if (successmessage != '')
{
//alertify.success(successmessage);
alert('record is inserted');
}
});
popup();
</script>
To avoid section is not defined error you need to call RenderSection as below.
#RenderSection("alertpopup", false)
And to make the pop up work, you have defined your javascript function but you are not calling you function anywhere. you can do this instead.
<script src="https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.13.1/alertify.min.js" type="text/javascript"></script>
<script>
function popup () {
var successmessage = '#ViewBag.message'
if (successmessage != '')
{
alertify.success(successmessage);
}
}
popup();
</script>
If you return View("create"), so you should render your section in Create.cshtml Or define this #RenderSection("alertpopup", false) in your Layout
Rendering sections take two parameters; a string and a boolean as such:
#RenderSection(string name, bool required)
The name parameter is name of the section to render and required indicates that the section must always be rendered. If the section may not be rendered in some views or sometime, you should set required to false like below.
#RenderSection("alertpopup", false)
I'm also not sure when you want your popup to display because it is not called in your code. If for whatever reason you'll want it to be called when your documents loads, you should change your code to this
#section alertpopup
{
<script src="https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.13.1/alertify.min.js" type="text/javascript">
$(doucument).ready(function () {
var successmessage = '#ViewBag.message'
if (successmessage != '')
{
alertify.success(successmessage);
}
});
</script>
}

Spring boot Rest thymeleaf javascript is not returning HTML

HI I am trying the example given in spring.io getting started guide.
it doesn't show any error but I am not getting HTML view
when I open the link http://localhost:8070/testJson in my browser all it shows is a JSON output like this
{"id":1,"content":"Hello World !"}
But I want it to show a proper HTML view, and I can not use #Controller here, I want to show HTML using Jquery javascript, How can I do that?
here is my controller method
#RestController
public class MyRestController {
private final Long counter = 1l;
#GetMapping("/testJson")
public TestJsonDto getTestJson(){
TestJsonDto testJsonDto=new TestJsonDto(counter,
"Hello World !");
return testJsonDto;
}
}
This is my Data class
public class TestJsonDto {
private Long id;
private String content;
public TestJsonDto(Long id, String content) {
this.id = id;
this.content = content;
}
public TestJsonDto() {
}
/*
GETTERS AND SETTERS WILL GO HERE
*/
And Below is my application class
#SpringBootApplication
#EnableJpaRepositories
public class MyjarApplication {
public static void main(String[] args) {
SpringApplication.run(MyjarApplication .class, args);
}
}
My Html file is
<!DOCTYPE html>
<html>
<head>
<title>Hello jQuery</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script src="/my.js"></script>
</head>
<body>
<div>
<p class="greeting-id">The ID is </p>
<p class="greeting-content">The content is </p>
</div>
</body>
</html>
and finally, this is my javascript
$(document).ready(function() {
$.ajax({
url: "http://localhost:8070/testJson"
}).then(function(testJsonDto) {
$('.greeting-id').append(testJsonDto.id);
$('.greeting-content').append(testJsonDto.content);
});
});
my application.properties is here
server.port=8070
Location of my.js is under src/main/resources/static/my.js
If you want to add a front end that can interact with your API you can structure your app like this:
This code setup your application, including static resources, for instance your resource/static/index.html will be render for root path localhost:8090 unless you wire this path in any controller(make sure root is not implicitly/explicitly user in any other #Controller or annotation).
#SpringBootApplication
#EnableJpaRepositories
public class MyjarApplication {
public static void main(String[] args) {
SpringApplication.run(MyjarApplication .class, args);
}
}
So, a simple way to render the HMTL you want is by putting that HTML at resource/static/index.html:
<!DOCTYPE html>
<html>
<head>
<title>Hello jQuery</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script src="/my.js"></script>
</head>
<body>
<div>
<p class="greeting-id">The ID is </p>
<p class="greeting-content">The content is </p>
</div>
</body>
</html>
and js should be placed at resource/static/my.js:
$(document).ready(function() {
$.ajax({
url: "http://localhost:8070/testJson"
}).then(function(testJsonDto) {
$('.greeting-id').append(testJsonDto.id);
$('.greeting-content').append(testJsonDto.content);
});
});
In your rest controller, path /testJson will be attended by getTestJson():
#RestController
public class MyRestController {
private final Long counter = 1l;
#GetMapping("/testJson")
public TestJsonDto getTestJson(){
TestJsonDto testJsonDto=new TestJsonDto(counter,
"Hello World !");
return testJsonDto;
}
}
So you access localhost:8090 to get the front-end, and thru javascript you access localhost:8090/testJson to get your API.

How to pass values from Spring Controller to jsp page?( the passed values is to be used to intialise javascript variables in jsp page

Below is my Spring Controller code.My intention is to pass the values of variables int a, int b, int c to the Jsp page ADMINRESULTS.
Please note that the values of these variables are to be used to intialise javascript variables in adminhome jsp page
#RequestMapping("/adminresults") //this is called by form action. This does not refer to adminhome jsp page
public String adminhome(Map<String, Object> model) {
ArrayList<Block> blockChain = NoobChain.getBlockChain();
Map<String, Integer> dataMap = new HashMap<String, Integer>();
if (!blockChain.isEmpty()) {
if (!NoobChain.isChainValid(blockChain)) { //if not valid to print the data.
model.put("tampermsg", "Unathorized acess detected and vote data is attacked.Correct values are ");
dataMap = NoobChain.validChainData(blockChain);
} else {
dataMap = blockChain.get(0).getData();
}
}
String blockchainJsonFromFile = new GsonBuilder().setPrettyPrinting().create().toJson(blockChain);
System.out.println("after.." + blockchainJsonFromFile);
model.put("message", "\n" + dataMap);
System.out.println("Before extracting DATA is "+dataMap);//to check the format of data map
int a=0;
int b=0;
int c=0;
if (dataMap.containsKey("A"))
{
a = dataMap.get("A");
System.out.println("value for key \"A\" is:- " + a);
}
if (dataMap.containsKey("B"))
{
b = dataMap.get("B");
System.out.println("value for key \"B\" is:- " + b);
}
if (dataMap.containsKey("C"))
{
c = dataMap.get("C");
System.out.println("value for key \"C\" is:- " + c);
}
model.put("a", a);
model.put("b", b);
model.put("c", c);
return "adminhome"; //significance of this code is to return adminhome jsp page
}
Below is a code snippet from adminhome jsp page
<html>
<head> </head>
<body>
<script type="text/javascript">
var as=8,cs=1,bs=4;
</script>
</body>
</html>
My intention is to intialise the above variables as,bs,cs with int a, int b, int c(from the Spring Controller Mentioned above)
Send json object from controller and assign to your hidden variable on html and use that object in your java script.
Below is code, just a sudo code below
Inside Controller
List<Someclass> list = new ArrayList<>();
Someclass someClass = new Someclass();
someClass.setKey("a");
someClass.setValue(1);
list.add(someClass);
Gson gson = new Gson();
ModelAndView modelAndView = new ModelAndView("adminhome");
modelAndView.addObject("list", gson.toJson(someClass));
JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<script type="text/javascript">
$(document).ready(function() {
var someClassJson = $('#"admin"');
list admins = JSON.parse(someClassJson.val());
for (var i = 0; i < admins.lenth; i++) {
var item = admins[i];
console.log(someClass.key);
console.log(someClass.value);
}
});
</script>
<head>
<title>Admin Example</title>
<script src="jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="personScript.js"></script>
</head>
<body>
<h1>
<Admin/h1> <input type="hidden" id="admin" value="${list}"/>
</body>
</html>
hope this will help.
Found an easy answer,Thank you Sanjay for helping,Also Nishant Raj(check out his code too,as Im a beginner ,I couldn't implement his code)
In the adminhome jsp page
<html>
<head> </head>
<body>
<script type="text/javascript">
var aa="${a}",bb="${b}",cc="${c}";
</script>
</body>
</html>
The above will fetch the values to javascript variables aa,bb,cc etc from the spring controller.
But please note if the fetched values if need to be used as Integer it must be converted.Presently it is of String type.
The code for it is.
<html>
<head> </head>
<body>
<script type="text/javascript">
var aa="${a}",bb="${b}",cc="${c}";
var as=parseInt(aa),cs=parseInt(cc),bs=parseInt(bb);
</script>
</body>
</html>
The parseInt will convert it into integer for using it in some future functions if needed.
Thank You all, Issue solved :)

How to display alert message in view page using viewbag

In Cshtml the following doesn't work
ViewBag.alert = #"<script language='javascript'>alert('Plan Already Exists');</script>";
How can i achieve this
I am using MVC Razor with C#, and I got this logic to work in my view by updating it a bit:
#if (!string.IsNullOrEmpty(ViewBag.Message))
{
<script type="text/javascript">
alert("#ViewBag.Message");
</script>
}
You need to pass ViewBag.alert as string to alert() function. Currently you are assign string to ViewBag.alert
Use
<script>
alert('#ViewBag.alert');
</script>
You need to add a message to the ViewBag in your controller.
public ActionResult Index() {
ViewBag.Message = "Plan Already Exists";
return View();
}
And then in your view, add a bit of script:
<% if (!string.IsNullOrEmpty(ViewBag.Message)) { %>
<script type="text/javascript">
alert('<%=ViewBag.Message%>');
</script>
<% } %>
You Can Use Like this:
Controller:
public ActionResult Index()
{
ViewBag.msg = "View Bag Value";
return View();
}
View:
if (!string.IsNullOrEmpty(ViewBag.msg))
{
<script type="text/javascript">alert('#ViewBag.msg');</script>
}

Categories

Resources