I have an Index.cshtml Page in MVC3 Razor View Engine with Following Code:
#{
ViewBag.Title = "Home Page";
}
<h2>#ViewBag.Message</h2>
<label id="lblClickMe" style="cursor:pointer"> Test Java Script Work in MVC Razor</label> || <label id="lblReset" style="cursor:pointer"> Rest </label>
<br /><br /><br /><br />
<input type="text" id="txtResult" style="width:300px"/>
And i have some JavaScript in Sane page Like :
<script type="text/javascript">
$("#lblClickMe").click(function () {
var txtResukt = document.getElementById("txtResult");
txtResukt.value = "Java script work successfully";
})
$("#lblReset").click(function () {
var txtResukt = document.getElementById("txtResult");
txtResukt.value = "";
})
</script>
When I try to load my view give following exception from "lblClickMe" Click Event :
Microsoft JScript runtime error: Object expected
Any one fix this bug?
Try this:
<script src="#Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<script type="text/javascript">
$("#lblClickMe").click(function () {
$("#txtResult").val("Java script work successfully");
});
$("#lblReset").click(function () {
$("#txtResult").val("");
});
</script>
Try this:
$(document).ready(function()
{
$("#lblClickMe").click(function () {
var txtResukt = document.getElementById("txtResult");
txtResukt.value = "Java script work successfully";
})
$("#lblReset").click(function () {
var txtResukt = document.getElementById("txtResult");
txtResukt.value = "";
})
});
This ensures the HTML in the page is loaded first before code attempts to wire up the click events.
Why not do this?
$("#lblClickMe").click(function () {
document.getElementById("txtResult").value = "Java script work successfully";
});
or in pure jQuery:
$("#lblClickMe").click(function () {
$("#txtResult").val("Java script work successfully");
});
Related
I have a set of KPI data I need to pass over to a Javascript file from my ASP.NET project. I thought I could do so using a ViewBag... Here is what is in the controller:
public ActionResult KPI()
{
if (Session["OrganizationID"] == null)
{
return RedirectToAction("Unauthorized", "Home");
}
else
{
int orgId;
int.TryParse(Session["OrganizationID"].ToString(), out orgId);
var user = db.Users.Find(User.Identity.GetUserId());
var organization = user.Organizations.Where(o => o.OrganizationID == orgId).FirstOrDefault();
var reports = db.Reports.ToList();
try
{
var org_reports = (from r in reports
where r.OrganizationID == organization.OrganizationID
select r).ToList();
var kpi = new KPI(org_reports);
var jsonKPI = JsonConvert.SerializeObject(kpi);
ViewBag.orgData = jsonKPI;
}
catch (ArgumentNullException e)
{
return RedirectToAction("Unauthorized", "Home");
}
}
return View();
}
From the View I've tried using hidden values, and also just passing them in as parameters when calling the script:
<input type="hidden" id="orgData" value=#ViewBag.orgData>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="~/Scripts/KPIs.js">
orgData = #ViewBag.orgData;
</script>
I then want to read this value in my JS script and parse it into JSON from the string:
function myFunction(){
var test1 = JSON.parse(document.getElementById('orgData'); // Doesn't work
var test2 = JSON.parse(orgData); // Doesn't work
}
It doesn't appear that any of these methods are working. What is my mistake here?
You should use Html.Raw, to avoid ASP.NET to escape your value:
orgData = #Html.Raw(ViewBag.orgData);
Also, if this is a Json, it is also a valid JS object, so you don't need to parse, it already is a JS Object.
It looks like you forgot the quotes.
<input type="hidden" id="orgData" value=#ViewBag.orgData>
should be
<input type="hidden" id="orgData" value="#ViewBag.orgData">
Also the code inside your script tag will never get executed because the script tag has a src attribute on it. Code inside script tags with src attributes never gets executed.
<script type="text/javascript" src="~/Scripts/KPIs.js">
orgData = #ViewBag.orgData;
</script>
should be changed to
<script type="text/javascript" src="~/Scripts/KPIs.js" />
<script>
orgData = #ViewBag.orgData;
</script>
I solved it! Pass the KPI model through the view and then it's as easy as:
var orgData = #Html.Raw(Json.Encode(Model));
Thanks to all to offered help.
I am working on an add-on for Confluence. I am using Apache Velocity and Js.
When I print out my template, I get no return from my JS file where I am using jQuery. How can I establish the communication between those two correctly? Thank you!
My JS
jQuery(function ($) {
var initmyConfluenceMacro = function ()
{
$(".myConfluenceMacro").each(function()
{
var html = "wadup";
var dayDates = $(this).find("input.dayDates").val();
html = html + dayDates;
$(this).html(html);
});
};
$(document).ready(function()
{
initmyConfluenceMacro();
});
});
MY Velocity Template.vm
#requireResource("confluence.web.resources:jquery")
#requireResource("com.atlassian.tutorial.myConfluenceMacro:myConfluenceMacro-resources")
My variables : $myCustomVar
My variable js:
<div class="myConfluenceMacro">
<fieldset class="parameters hidden">
<input type="hidden" class="dayDates" value="YO! Was up dude?">
</fieldset>
</div>
I managed it. Like this, it is working, and I get the HTML back!
JS
$(document).ready(function(){
$(".myConfluenceMacro").each(function(){
$(this).html("Hello <b>world!</b>");
});
});
VELOCITY
<script type="text/javascript">
#include( "templates/currencyDetail.js")
</script>
<body>
<div class="myConfluenceMacro">
</div>
I'm currently getting up to speed with SignalR, and tried to build a very basic message notification system using the very basic understanding of SignalR that I have but I can't get the messages to come back after the submission.
I've read up on numerous blogs on the topic and the very basic is to have a VOID method that accepts a string value and then passes that back by attaching it to the Clients context, however, this does not work for, as onReceiveNotification() is always undefined in JS debugger?
Am I missing something
notificationhub.cs
[HubName("notificationHub")]
public class NotificationHub : Hub
{
public override System.Threading.Tasks.Task OnConnected()
{
return base.OnConnected();
}
public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled)
{
return base.OnDisconnected(stopCalled);
}
public override System.Threading.Tasks.Task OnReconnected()
{
return base.OnReconnected();
}
[HubMethodName("sendNotifications")]
public void SendNotifications(string message)
{
Clients.All.onRecieveNotification(string.Format("{0} {1}", message, DateTime.Now.ToString()));
}
}
message.html page
<div>
<input type="text" id="messageinput" />
<button id="notifybutton">Send Message</button>
</div>
<script src="Scripts/jquery-2.1.4.min.js"></script>
<script src="Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="signalr/hubs"></script>
<script type="text/javascript">
jQuery(document).ready(function ($)
{
var $hub = $.connection.notificationHub;
$.connection.hub.start();
$(document).on("click", "#notifybutton", {}, function (e)
{
e.preventDefault();
var $message = $("#messageinput").val();
$hub.server.sendNotifications($message);
});
});
</script>
display.html
<div>
<ul id="messages"></ul>
</div>
<script src="Scripts/jquery-2.1.4.min.js"></script>
<script src="Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="signalr/hubs"></script>
<script type="text/javascript">
jQuery(document).ready(function ($)
{
var $hub = $.connection.notificationHub;
$hub.onRecieveNotification = function (message)
{
$("#message").append($("<li></li>", { text: message }));
}
$.connection.hub.start();
});
</script>
It looks like you are missing client in:
$hub.client.onRecieveNotification = function (message)
{
$("#message").append($("<li></li>", { text: message }));
}
I am testing putting a text editor on my page and storing it as part of a JSON object.
HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://tinymce.cachefly.net/4.0/tinymce.min.js" type="text/javascript"> </script>
<script type="text/javascript">
tinymce.init({
selector: "textarea"
});
</script>
<link rel="stylesheet" href="/jquery.mobile-1.3.2.min.css"/>
<script src="/jquery-1.9.1.min.js"></script>
<script src="/jquery.mobile-1.3.2.min.js"></script>
</head>
<body>
<form method="post" action="formSubmit.js">
<textarea name ="editor"></textarea>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
JS
$(document).ready(function () {
var text = $("editor").val();
var name = "project name";
var id = 5;
var item = new item(name, text, id);
var itemArray = localStorage.items;
if (itemArray == undefined) {
itemArray = [];
} else {
itemArray = JSON.parse(itemArray);
}
itemArray.push(item);
localStorage.items = JSON.stringify(itemArray);
});
I want to be able to store item in a JSON object. When I run this I receive a "not-well formed" error at line 1 of the Javascript. It's a very simple program I'm running and can't seem to pinpoint what is causing the error. Is the JSON done incorrectly or are scripts in my HTML header causing issues?
$("editor") is looking for an html tag called 'editor'. you probably want to attach an id attribute to your and do $('#editor')
I have a textbox where i must to write a value, how to pass this value in my controller if I call my controller using ActionLink, this is my code:
view:
#Html.TextBox("tisch", "", new { #class = "teschChange"})
#Html.ActionLink("Apply Command", "ApplyCommand", "Work")
and this is te script
<script type="text/javascript">
$(function test() {
$(".teschChange").change(function () {
var tisch = $(this).attr('value');
});
});
</script>
I must to send tisch in ApplyCommandController
Thanks
Instead of using an action link, use a standard link:
<a id="l" href="#Url.Action("ApplyCommand", "Work")">Apply Command</a>
Then, you can use this script:
<script type="text/javascript">
$(function test() {
$(".teschChange").change(function () {
var tisch = $(this).attr('value');
$("#l").attr("href", "#Url.Action("ApplyCommand", "Work")/" + tisch);
});
});
</script>
Which will assign a href of: /Work/ApplyCommand/tisch.
this was the correct script:
$("#l").attr("href", "#Url.Action("ApplyCommand", "Work")?tisch=" + tisch);