How to call external javascript function to ClientSideEvents.Click event? - javascript

I have DevExpress().Button on a website which should take specific grid value from a focused row and pass it to external function.
Here is my button:
#Html.DevExpress().Button(
settings =>
{
settings.Name = "btnMyName";
settings.Width = 120;
settings.Height = 25;
settings.Text = "MyText";
settings.Styles.Native = true;
settings.ClientEnabled = true;
settings.ClientSideEvents.Click = "function(s, e) { gridView.GetRowValues(gridView.GetFocusedRowIndex(), 'MyValue', OnGetRowValues); }";
}).GetHtml()
I simply can't reach OnGetRowValues function - always get the same exception:
Uncaught ReferenceError: OnGetRowValues is not defined
I have the script in the same folder as my .cshtml file and tried to reference it with <script src=""></script> in relative and absolute way. I tried to put the code to function directly between script tags to the cshtml page but nothing works and I get always the same error. The only solution which so far worked was to put the entire script as assingment to ClientSideEvents.Click but because the OnGetRowValues function is big, it will become messy and downright unpractical solution. Any help will be appreciated.

Go through Client-Side Events documentation and implement using below example:
<script type="text/javascript" src="~/Content/js/index.js"></script>
<script type="text/javascript">
function ButtonClick(s,e)
{
gridView.GetRowValues(gridView.GetFocusedRowIndex(), 'ShipName', OnGetRowValues);
}
</script>
#Html.DevExpress().Button(settings =>
{
settings.Name = "btnGetSelectedRowValue";
settings.UseSubmitBehavior = true;
settings.ClientSideEvents.Click = "ButtonClick";
}).GetHtml()
#Html.Action("GridViewPartial")
index.js
// Value contains the "EmployeeID" field value returned from the server, not the list of values
function OnGetRowValues(Value) {
// Right code
alert(Value);
// This code will cause an error
// alert(Value[0]);
}
Hope this help..

Related

How to pass values to an external Javascript script from ASP.NET

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.

How can I populate an embedded website form with URL parameters using Javascript?

I have a Zoho form embedded on a Squarespace site and I need to populate some fields with URL parameters in Javescript. I'm using the following code to get the parameters:
<script> function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
</script>
and then to set the parameters to variables:
var campaign1 = getUrlVars()["campaign"];
alert(campaign1);
So that gets the parameter named 'campaign' in the url and assigns it to 'campaign1'. The alert is just to show that it is working, and it is. Then I want to run this:
<script type="text/javascript" src="https://forms.zohopublic.com/....j7Q?campaign="+campaign1 id="ZFScript"> alert(campaign1); </script>
But no matter what I do I can't get that part to reference the variable in the 'src=' section, but I can reference it in the 'alert(campaign1);' immediately after.
I also tried this, which was meant to save the whole URL to a variable named 'site' and just run 'src=site', but that didn't work either.
<script> function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var campaign1 = getUrlVars()["campaign"];
var site = "https://forms.zohopublic.com....j7Q?campaign="+campaign1
</script>
<script type="text/javascript"
src=site id="ZFScript"> alert(site);</script>
Your issue is that you are trying to write some js code where it is not parsed/rendered/executed.
The js code will be executed inside <script> tags or onEvent attributes. For instance onclick or onload.
So what you want to do is execute some js code inside a script tag that will generate a script tag with the dynamic src attribute you are trying to achieve. This is a way of doing it:
<script type="text/javascript">
// [...]
var campaign1 = getUrlVars()["campaign"];
var site = "https://forms.zohopublic.com....j7Q?campaign="+campaign1;
// create a script node
var scriptElement = document.createElement('script');
// set its src attribute
scriptElement.setAttribute('src', site);
// add you new script node to your document
document.body.appendChild(scriptElement);
</script>

javaScript local script can't find function in src script

I have a javaScript source file, named LIMDU.js, that contains a var and a function, like this --
var SessionTimeOutID;
function KeepSessionAlive() {
var sessionTimeoutWarning = #Session.Timeout;
var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
clearTimeout(SessionTimeOutID);
SessionTimeOutID = setTimeout('SessionEnd()', sTimeout);
function SessionEnd() {
window.location = "/Account/LogOff";
}
}
and in the cshtml file, I have this:
<script type="text/javascript" src="~/Scripts/LIMDU.js"></script>
<script>
$(document).ready(function () {
KeepSessionAlive();
});
</script>
but when I try to execute the code, I get the error "KeepSessionAlive" not found.
I thought that the src code would be loaded before the local script code was executed; if that's not the case, how do I refer to a function in my local script block that's defined in a src'd file?
Check your console. Your LIMDU.js file is not compiling (probably undefined #Session ?)

Javascript Dojo development script error

An interesting problem about dojo toolkit and javasacript.
I am using a visual studio to developing application
I have created a module as following and named its file as calc.js
djConfig.js
var pathRegex = new RegExp(/\/[^\/]+$/);
var locationPath = location.pathname.replace(pathRegex, '');
var dojoConfig = {
async: true,
packages: [
{
name: 'application',
location: locationPath + '/js/application'
}
};
calc.js
define(["dojo/_base/declare"], function(declare) {
return declare(null, {
Sum: function(x,y) {
return x + y;
}
}); })
Once created this file I references this file in index.html file as following,
index.html
<script type="text/javascript" src="/js/application/djConfig.js"></script>
<script type="text/javascript">
require(["application/calc"],
function(calc) {
var c = new calc();
console.log(c.Sum(1, 2));
}
);
</script>
This code is wirking at first.Calculating sum and writing in concole of browser.
But than I am changing something in calc.js (ex. return x+y-1;).
The browser is giving a script error.
If I change something in index.html page - for example type a whitespace- than script is working.
All changes in calc.js file is throwing script error, if I do not change somewhere in index.html
Even If I type a whitespace or add a line in index page, every thing is working.
Did you encounter a problem like this?

How to make the jQuery valid function work reliably on IE?

I have a problem on jQuery valid function. When on IE, it doesn't work, the valid always return true. I used this code: client side validation with dynamically added field
Here's the chart:
Chrome IE
jquery-1.6.1 works not working
jquery-1.4.4 works works
1.6 doesn't work on IE too. However, 1.4.4 jQuery valid works on IE.
Here's the jsFiddle-friendly test (test this as local html):
<!--
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8/jquery.validate.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
<form id="XXX">
<input type="submit" id="Save" value="Save">
</form>
<script type="text/javascript">
// sourced from https://stackoverflow.com/questions/5965470/client-side-validation-with-dynamically-added-field
// which I do think don't have a bug
(function ($) {
$.validator.unobtrusive.parseDynamicContent = function (selector) {
//use the normal unobstrusive.parse method
$.validator.unobtrusive.parse(selector);
//get the relevant form
var form = $(selector).first().closest('form');
//get the collections of unobstrusive validators, and jquery validators
//and compare the two
var unobtrusiveValidation = form.data('unobtrusiveValidation');
var validator = form.validate();
$.each(unobtrusiveValidation.options.rules, function (elname, elrules) {
if (validator.settings.rules[elname] == undefined) {
var args = {};
$.extend(args, elrules);
args.messages = unobtrusiveValidation.options.messages[elname];
$('[name=' + elname + ']').rules("add", args);
} else {
$.each(elrules, function (rulename, data) {
if (validator.settings.rules[elname][rulename] == undefined) {
var args = {};
args[rulename] = data;
args.messages = unobtrusiveValidation.options.messages[elname][rulename];
$('[name=' + elname + ']').rules("add", args);
}
});
}
});
}
})($);
// ...sourced from others
// my code starts here...
$(function () {
var html = "<input data-val='true' " +
"data-val-required='This field is required' " + "name='inputFieldName' id='inputFieldId' type='text'/>";
$("form").append(html);
var scope = $('#XXX');
$.validator.unobtrusive.parseDynamicContent(scope);
$('#Save').click(function (e) {
e.preventDefault();
alert(scope.valid());
});
});
// ...my code ends here
</script>
UPDATE
I tried my code on jsFiddle, it has side-effect, the jQuery 1.6's valid is working on IE. Don't test this code on jsFiddle. Test this code on your local html
This problem has been solved. try version 1.8.1.
Download jQuery validation plugin
Hi I also got the same problem and I have updated my both scripts file to the latest one and everything is working very fine on my side. Go to jquery.com and check for the latest jquery code file.

Categories