Javascript function with name from ViewBag - asp.net-mvc

How to generate javascript function with the name taken from ViewBag? I'm trying the below
#{ (ViewBag.ModuleId + "DatePickerStartDateChange = function() {console.log('asdf');};");}
and hoping that it will emit javascript in the html output as
xxxxxxDatePickerStartDateChange = function() {alert("asdf");};

Absolutely no idea why on earth you would need to do that, but here's the correct syntax:
<script type="text/javascript">
#(ViewBag.ModuleId)DatePickerStartDateChange = function() {
console.log('asdf');
};
</script>

Related

jquery mobile: Object [object Object] has no method 'jqmData'

I am relatively new to Jquery and Jquery mobile, I was just trying and tutorial to add Loading animation on the page, I was simply following the code provided in one of the demos. However I am getting the following error.
Uncaught TypeError: Object [object Object] has no method 'jqmData'
I am using the following code snippet and javascript
<button class="show-page-loading-msg ui-btn-right" data-icon="refresh" data-theme="d" data-textonly="false" data-textvisible="true" data-msgtext="Loading..." data-inline="true">Refresh</button>
<script>
window.$ = window.jQuery = WLJQ;
$( document ).on( "click", ".show-page-loading-msg", function() {
var $this = $( this ),
theme = $this.jqmData( "theme" ) || $.mobile.loader.prototype.options.theme,
msgText = $this.jqmData( "msgtext" ) || $.mobile.loader.prototype.options.text,
textVisible = $this.jqmData( "textvisible" ) || $.mobile.loader.prototype.options.textVisible,
textonly = !!$this.jqmData( "textonly" );
html = $this.jqmData( "html" ) || "";
$.mobile.loading( "show", {
text: msgText,
textVisible: textVisible,
theme: theme,
textonly: textonly,
html: html
});
setTimeout(WL.Client.reloadApp, 5000);
$.mobile.loading( "hide" );
});
</script>
The error is pointing to this line in the javascript theme = $this.jqmData( "theme" )
when i debugged on browser console i was able to see the button data values assigned to the $this variable
Please advice,
if you run the following:
console.log($.mobile.version);
... and check the console. Does it print out the version? Or does it say it is undefined?
If it is undefined, check if you have correctly referenced jQuery and jQuery mobile libraries, something like this:
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css">
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
Try to put your script into the 'mobileinit' event handler (or a page event handler), like:
<script src="js/jquery-2.0.3.js"></script>
<script>
window.$ = window.jQuery = WLJQ;
$(document).on('mobileinit', function() {
// your script
});
</script>
<script src="jqueryMobile/jquery.mobile-1.3.1.js"></script>
NOTE the sequence of the script

Replacing 'url' method in Jquery UI 1.9 Tabs

I am working on a web application and was making great progress using JQuery UI Tabs, specifically the 'url' method of dynamically updating the target url of the ajax request which was bound to each tab. I have created a simplified example here:
Each of the 2 Tabs, function 1 & function 2, display the results of some tests based on the parameters that are passed to the test. The tests remain the same throughout, but I was changing the variables used in the functions by manipulating the url bound to the tab. The 'url' method of updating the url being called on a lazy loading Tab allowed me to do this, but its now been deprecated and won't be supported at all soon. So I have been searching for a way to do this using the 'beforeLoad' event in JQuery UI 1.9.
The suggestion was that one could manipulate the ui.ajaxSettings to set the data parameter but there is a bug (http://bugs.jqueryui.com/ticket/8673), and it appears this won't be fixed. The workaround suggested is to manipulate the ui.ajaxSettings.url instead.
My working example is below, but I'm not sure if this is the cleanest / most appropriate way to achieve what I'm after and any suggestions would be most welcome. I struggled to find examples on how to do even this much, so hopefully it will help someone else in a similar situation.
<title> Jquery Tabs AJAX Test</title>
<script type="text/javascript" src="js/jquery-1.8.2.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.9.1.custom.js"></script>
<link rel="stylesheet" type="text/css" href="css/smoothness/jquery-ui-1.9.1.custom.css">
</head>
<body >
<script type=text/javascript>
$(document).ready(function() {
$( '#tabs' ).tabs({ });
$('button.set_variable').click(function() {
var variable = $(this).val();
$( '#tabs' ).tabs({
beforeLoad: function( event, ui ) {
ui.ajaxSettings.url += "&variable=" + variable ;
}
});
var selected_tab = $('#tabs').tabs('option', 'selected');
$( '#tabs' ).tabs("load", selected_tab);
});
})
</script>
<button class="set_variable" value="1">Variable = 1</button>
<button class="set_variable" value="2">Variable = 2</button>
<button class="set_variable" value="3">Variable = 3</button>
<div id="tabs" >
<ul>
<li>Function 1 </li>
<li>Function 2 </li>
</ul>
</div>
</body></html>
N.B. The ajax.php file here just echos back what was passed to it.
<?php
extract($_GET);
var_dump($_GET);
?>
You could do something like this too :
var variable = '';
$( '#tabs' ).tabs({ beforeLoad: function( event, ui ) {
if(variable != '')
ui.ajaxSettings.url += "&variable=" + variable ;
}});
$('button.set_variable').click(function() {
variable = $(this).val();
});
http://jsfiddle.net/DNWzY/1/

jQuery never called

I'm trying to implement the solution provided in this question here:
How to pass Model Value through ActionLink
So in my view I have an action link
#Html.ActionLink("Look up registration", "RegLookup", "Vehicle", new {#id="check"},null)
And in a Javascript file I have :
$(function ()
{
$("#check").click(function (e) {
e.preventDefault();
}
I've cut the function down to just preventing the default action of the action link.
In the view I've also referenced the java script files
<script src="~/Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"></script>
<script src="~/Scripts/GetRegistrationPlate.js" type="text/javascript"></script>
However when I click on the action link the default method continues to fire.
What might I have missed?
For one there are many syntax errors. Try this
$(function () {
$("#check").click(function (e) {
e.preventDefault();
return false;
});
});
Edit: Also, change the ActionLink to
#Html.ActionLink("Look up registration", "RegLookup", "Vehicle", new { #id = "check" }, new { #id = "check" })
The first id is for the route, the second id is for the html element.

How to send parameter on function calling in "jQuery Ui Draggable Helper"?

I'm using jQuery UI plugin for drag'n drop my object, But I have a problem.
My html Source is like this:
<html>
<body>
<div id="firstDiv">some thing is here</div>
</body>
</html>
Now, I want to draggable the above div, using helper. My code is this:
<script type="text/javascript">
$(document).ready(function(){
$("#firsstDiv").draggable({helper:anImage});
});
function anImage() {
return '<img src="~/myImage.png" alt="" />';
}
</script>
Ok, this code is work as well, but I want to set image address, But when i change my function to have a parameter, that doesnt work, O_o
My new code is this:
<script type="text/javascript">
$(document).ready(function(){
$("#firsstDiv").draggable({helper:anImage($(this).text())});
});
function anImage(address) {
return '<img src="'+address+'" alt="" />';
}
</script>
but not working.
Thanks for your helps.
OK - you can't pass a parameter into your helper function. I'm pretty sure that's the problem.
The way around this would be to create a setup function and then call your anImage function from there:
$(function(){
$("#firsstDiv").draggable({
helper: setup
});
});
// function to setup draggable DOM elements
function setup() {
anImage("~/myImage.png");
// ... do other setup things here too
}
function anImage(imageAddress) {
return '<img src="'+imageAddress+'" alt="" />';
}
Unless of course you are trying to call anImage with a different image address for each draggable element, in which case the above will not work. But you shouldn't be using the helper function to do this anyway as I'm pretty sure it's just meant to contain code to setup all of the draggable elements you are creating.
Hope this helps,
James

How do I write unencoded Json to my View using Razor?

I'm trying to write an object as JSON to my Asp.Net MVC View using Razor, like so:
<script type="text/javascript">
var potentialAttendees = #Json.Encode(Model.PotentialAttendees);
</script>
The problem is that in the output the JSON is encoded, and my browser doesn't like it. For example:
<script type="text/javascript">
var potentialAttendees = [{"Name":"Samuel Jack"},];
</script>
How do I get Razor to emit unencoded JSON?
You do:
#Html.Raw(Json.Encode(Model.PotentialAttendees))
In releases earlier than Beta 2 you did it like:
#(new HtmlString(Json.Encode(Model.PotentialAttendees)))
Newtonsoft's JsonConvert.SerializeObject does not behave the same as Json.Encode and doing what #david-k-egghead suggests opens you up to XSS attacks.
Drop this code into a Razor view to see that using Json.Encode is safe, and that Newtonsoft can be made safe in the JavaScript context but is not without some extra work.
<script>
var jsonEncodePotentialAttendees = #Html.Raw(Json.Encode(
new[] { new { Name = "Samuel Jack</script><script>alert('jsonEncodePotentialAttendees failed XSS test')</script>" } }
));
alert('jsonEncodePotentialAttendees passed XSS test: ' + jsonEncodePotentialAttendees[0].Name);
</script>
<script>
var safeNewtonsoftPotentialAttendees = JSON.parse(#Html.Raw(HttpUtility.JavaScriptStringEncode(JsonConvert.SerializeObject(
new[] { new { Name = "Samuel Jack</script><script>alert('safeNewtonsoftPotentialAttendees failed XSS test')</script>" } }), addDoubleQuotes: true)));
alert('safeNewtonsoftPotentialAttendees passed XSS test: ' + safeNewtonsoftPotentialAttendees[0].Name);
</script>
<script>
var unsafeNewtonsoftPotentialAttendees = #Html.Raw(JsonConvert.SerializeObject(
new[] { new { Name = "Samuel Jack</script><script>alert('unsafeNewtonsoftPotentialAttendees failed XSS test')</script>" } }));
alert('unsafeNewtonsoftPotentialAttendees passed XSS test: ' + unsafeNewtonsoftPotentialAttendees[0].Name);
</script>
See also:
Does the output of JsonConvert.SerializeObject need to be encoded in Razor view?
XSS Prevention Rules
Using Newtonsoft
<script type="text/jscript">
var potentialAttendees = #(Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.PotentialAttendees)))
</script>

Resources