I will need to pass a java variable to a javascript function. I have my codes as below. Wondering is that the correct way?
Because I have some problem here when the page first load, and the button is clicked, the chartData and categories is empty.
I am expecting the below:
chartData = [{"name":"Anne","data":[1.0,0.0,4.0]},
{"name":"Billy","data":[5.0,7.0,10000.0]}]
categories = ["APPLES","BANANAS","ORANGES"]
public String doLoadChartDataAction () {
String _cat = "[{\"name\":\"Anne\",\"data\":[1.0,0.0,4.0]},{\"name\":\"Billy\",\"data\":[5.0,7.0,10000.0]}]";
String _data = "[\"APPLES\",\"BANANAS\",\"ORANGES\"]";
System.out.println("1.0 " + " _cat:" + _cat);
System.out.println("1.0 " + " _data:" + _data);
setCategories(_cat);
setChartData(_data);
return "";
}
<p:commandButton styleClass="commandButton" value="This" id="btnThis" action="#{pc_Test.doLoadChartDataAction}"
oncomplete="renderChart('container','line','Sample Chart','${pc_Test.chartData}', '${pc_Test.categories}');">
</p:commandButton>
public String doLoadChartDataAction () {
String _cat = "[{\"name\":\"Anne\",\"data\":[1.0,0.0,4.0]},{\"name\":\"Billy\",\"data\":[5.0,7.0,10000.0]}]";
String _data = "[\"APPLES\",\"BANANAS\",\"ORANGES\"]";
System.out.println("1.0 " + " _cat:" + _cat);
System.out.println("1.0 " + " _data:" + _data);
//setCategories(_cat);
//setChartData(_data);
RequestContext context = RequestContext.getCurrentInstance();
context.addCallbackParam("chartData", _data);
context.addCallbackParam("categories", _cat);
return "";
}
<p:commandButton styleClass="commandButton" value="This" id="btnThis" action="#{pc_Test.doLoadChartDataAction}"
oncomplete="renderChart('container','line','Sample Chart', args.chartData, args.categories);">
Related
How can i execute a C# method from JavaScript Code without refreshing the page?
this is the function that i want to execute:
protected void submitData(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection();
string worker = workerNameInput.Text;
string project = projectNameInput.Text;
string status = statusInput.Text;
string color = colorInput.Text;
if (worker.Equals("") || project.Equals("") || status.Equals("") || color.Equals(""))
return;
try
{
conn = new MySqlConnection();
conn.ConnectionString = connectionString;
conn.Open();
string com = "insert into " + table + " values ('" + worker + "','" + project + "','"+ status + "','"+ color + "');";
MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand(com, conn);
string res = command.ExecuteNonQueryAsync().ToString();
Console.WriteLine(res);
Console.WriteLine("Insert command pass successfully");
}
catch (Exception ex)
{
Console.WriteLine("Failed to update database with \"insert\" command");
Console.WriteLine(ex.Message);
}
}
and i know that i should use
public partial class Home : System.Web.UI.Page, IPostBackEventHandler
and
public void RaisePostBackEvent(string eventArgument)
{
submitData(null, null);
}
inside the JS i used this code:
project.updateTable = function() {
var projectName = project.projectName();
var workerName = project.workerName();
var status = project.status();
var color = project.color();;
if (projectName == "" || workerName == "" || status == "" || color == "")
return;
project.rows.push({ projectName: ko.observable(projectName), workerName: ko.observable(workerName), status: ko.observable(status), color: ko.observable(color) });
project.projectName("");
project.workerName("");
project.status("");
project.color("");
var argumentString = projectName + "," + workerName + "," + status + "," + color;
var pageId = '<%= enterToDB.ClientID%>';
__doPostBack(pageId, argumentString);
};
This is how i configure my button:
<p><asp:Button runat="server" ID="enterToDB" Text="Add Project" data-bind="click: updateTable" onmouseover="this.style.background='orange', this.style.color='darkslateblue'" onmouseout="this.style.background='darkslateblue', this.style.color='orange'" /></p>
Can you correct my mistakes please?
and show me where i'm wrong?
You can use ASP.NET WebForm's UpdatePanel control to run the code-behind async. This is commonly known as "AJAX" (Asynchronous JavaScript and XML) or "XHR" (XML HTTP Request), and is built-in to the WebForms framework.
Here's a great resource on MSDN to get you started: https://msdn.microsoft.com/en-us/library/bb399001.aspx
It is possible to call JavaScript functions from C# form or class and to call C# functions from the JavaScript.
Javascript to C#
-------C# code--------------------
[System.Runtime.InteropServices.ComVisible(true)]
// execute the following instruction in the form initialisation
WebBrowser1.ObjectForScripting = this ;
// define a public method
public void ShowMessage (string msg) { MessageBox.Show(msg); }
-------HTML and Javascript----------------
<input type="button" value="JavaScript is calling Dotnet"
onclick="window.external.ShowMessage('JavaScript message');" />
C# to Javascript
-------C# code--------------------
object [] MyArgs = { "Hello" } ; WebBrowser1.Document.InvokeScript("MyJsFunction",MyArgs ) ;
-------Javascript----------------
function MyJsFunction(s) { alert(s) ; }
This is my Get action method to get posts with their image:
public JsonResult GetPosts()
{
var ret = (from post in db.Posts.ToList()
orderby post.PostedDate descending
select new
{
PostedByName = post.ApplicationUser.UserName,
PostedByAvatar = _GenerateAvatarUrlForUser(post.PostedBy),
});
return Json(ret, JsonRequestBehavior.AllowGet);
}
and this is my GetFileData action method to retrieve the images from the database:
public FileResult GetFileData(int fileId)
{
var file = db.Files.Single(x => x.FileId == fileId);
return File(file.Content, file.ContentType);
}
and this is the method which will generate url:
private string _GenerateAvatarUrlForUser(int? Id)
{
var avatarImage = db.Files.SingleOrDefault(s => s.ApplicationUserId == Id);
if (avatarImage != null)
return Url.Action("GetFileData", new { fileId = avatarImage.FileId });
return String.Empty;
}
and this is the view page to show the user name with their pic but i am not able to show pic:
<div>
<div id="ajaxDiv">
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("/Post/GetPosts", null, function (data) {
var div = $('#ajaxDiv');
div.html("<br /> " + "Users received from server: " + "<br />");
$.each(data, function (i, item)
{
printUser(div, item);
});
});
});
function printUser(div, item)
{
div.append("<br/>" + "UserName: " + item.PostedByName + "<br/>" + "Pic: " + item.PostedByAvatar);
// I am stuck here on how to append image to this div or how to pass item.PostedByAvatar to this img src tag
div.append("<img src= + item. />");
<img src="#Url.Action("GetFileData", "Home", new { id = item.Id })" style="width:100px;height:100px;"/>
}
</script>
the url which i am successfullly getting back is like this:
/Post/GetFileData?fileId=2
how to resolve this ???
In your GetFileData action the parameter name in fileId. But when you are setting the source of image you are using the parameter name id which should be fileId like below.
#Url.Action("GetFileData", "Home", new { fileId = item.Id })
Update: As you said this should work.
div.append('<img class=cssClassName src="' + item.PostedByAvatar +'"/>');
I have some working code (jQuery/Javascript) that makes a call to an API and submits data to it. The same service then returns a success or failure message depending on whether the data was inserted into the API db. The below works flawlessly when loaded in the browser.
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
$(document).ready(function () {
var groupType = getParameterByName('group').trim();
if (groupType == 'm') {
groupId = 'ICM.RealLife.Mobile';
} else if (groupType == 'd') {
groupId = 'ICM.RealLife.Desktop';
}
var email = getParameterByName('email').trim();
var mobileTel = getParameterByName('mobile').trim();
var panelistId = mobileTel;
var password = 'icm001';
var locale = 'en';
alert('email=' + email + '\n\nMobile=' + mobileTel + '\n\nGroup=' + groupId);
if (mobileTel != '' && email != '' && groupId != '') {
//Build up querystring to pass to API
var dataString = "panelistId=" + (encodeURIComponent('+') + mobileTel) + "&groupId=" + groupId + "&emailAddress=" + email + "&password=" + password + "&locale=" + locale + "&mobileNumber=" + (encodeURIComponent('+') + mobileTel) + "";
//var apiResult;
//send to API
$.getJSON('https://www.analyzeme.net/api/server/prereg/?', dataString + '&callback=?', function (getResult) {
//apiResult = JSON.stringify(getResult);
//alert(apiResult);
});
//} else {
// alert('Incorrect parameters!');
}
});
I now have to get this working using a 1x1 tracking pixel using aspx like below;
<img src="http://www.somedomain.com/pixel.aspx?email=email#email.com&mobile=+441111222222&group=d" width="1" height="1"/>
BUT, I do not know how to get my JavaScript to fire in the asp.net page when it is hit? I know I need to do something with RegisterStartupScript but how do I get all that JS into it and how do I get it to fire when the page is hit. I know how to return an img/gif using response headers, so I am cool with that.
Help greatly appreciated! :)
Call the JS function from your Page_Load event in code behind. This will fire every time the page is loaded.
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(Page, GetType(), "myFunction", "myFunction();", true);
}
JavaScript
function myFunction() {
//Code you want to run from document.ready
}
I have a function onRowClick called RowClick and is working fine. I am trying to move it to a button and call the function from the code behind. For some reason is not triggering the function.. Anyone knows why and how I can fix this?
aspx.cs
if (e.CommandName == "Addvoucher")
{
GridDataItem item = (GridDataItem)e.Item;
var id = item.GetDataKeyValue("RowID");
ClientScript.RegisterStartupScript(Page.GetType(), "mykey", "RowClick("+id+");", true);
}
aspx
<script>
var popUpObj;
function RowClick(sender, eventArgs) {
var filterId = eventArgs.getDataKeyValue('RowID');
popUpObj = window.open("voucher.aspx?param=" + filterId + "",
"ModalPopUp",
"toolbar=no," +
"scrollbars=no," +
"location=no," +
"statusbar=no," +
"menubar=no," +
"resizable=0," +
"width=530," +
"height=500," +
"left = 450," +
"top=130"
);
popUpObj.focus();
LoadModalDiv();
}
function LoadModalDiv()
{
var bcgDiv = document.getElementById("divBackground");
bcgDiv.style.display="block";
}
function HideModalDiv() {
var bcgDiv = document.getElementById("divBackground");
bcgDiv.style.display = "none";
}
</script>
IN page voucher.aspx
<script type = "text/javascript">
function OnClose() {
if (window.opener != null && !window.opener.closed) {
window.opener.location.reload(); //refreshing parent when popup close
// window.opener.HideModalDiv();
}
//if (window.closed==true) window.open("~/routedoc.aspx");
}
window.onunload = OnClose;
</script>
Change your js function like this
function RowClick(filterId) {
popUpObj = window.open("voucher.aspx?param=" + filterId + "",
"ModalPopUp",
"toolbar=no," +
"scrollbars=no," +
"location=no," +
"statusbar=no," +
"menubar=no," +
"resizable=0," +
"width=530," +
"height=500," +
"left = 450," +
"top=130"
);
popUpObj.focus();
LoadModalDiv();
}
There is no need of this line now var filterId = eventArgs.getDataKeyValue('RowID'); Now you can directly use the parameter filterId in your js function.
Calling JavaScript function on code behind i.e. On Page_Load
ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);
If you have UpdatePanel there then try like this
ScriptManager.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);
Because you are calling RowClick() and in your code you are calling the second parameter eventArgs and actually it's an undefined value.
Make sure you pass the correct parameters.
Since you just calling a javscript function then I would recommend to just on the grid row data bound just assign the value to an anchor a tag or a button to just call the javascript.
The problem is you are not passing any arguments for that js function from server side but you are getting data key value in client function as in your edited question pass row id from server side and change the client side function as below,
function RowClick(rowId)
{
// use rowId
popUpObj = window.open("voucher.aspx?param=" + rowId + "",
}
I have some other javascript functions that are being set on the onfocus and onblur events of the textbox that I am using. In these functions it calls a generic javascript function that is not related to any controls. I want to know how to just simply spit this function out to the html of the page from the code behind. Something like this...
Page.ClientScript.RegisterStartupScript(this.GetType(), "?????", getCounter);
EDIT: Here is what I mean
public class MVADTextBox : TextBox
{
protected override void OnLoad(EventArgs e)
{
var getCounter = "<script language=\"javascript\">" +
"function GetCounter(input) {" +
//this function gets the number of special characters taht are in a row.
//it is only the grouping of characters that are right after your current position
"var textbox = document.getElementById(input.id);" +
"var mask = textbox.getAttribute('Mask');" +
"var inputCharacters = textbox.getAttribute('InputCharacters');" +
"var tbid = \"#\" + input.id;" +
"var position = $(tbid).caret().start;" +
"var counter = 0;" +
"for (var i = position; i < mask.length; i++) {" +
" if (mask[i] != '#') {" +
" counter++;" +
" if (mask[i + 1] == '#') {" +
" break;" +
" }" +
" }" +
"}" +
"return counter;" +
" }" +
"</script>";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OnFocus", onFocus);
Page.ClientScript.RegisterStartupScript(this.GetType(), "GetCounter(input)", getCounter);
var onBlur = "<script language=\"javascript\"> function PopulateField(input) {if (input.value == \"\") {input.value = input.defaultValue; input.className = 'sampleText'; } } </script>";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OnFocus", onFocus);
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OnBlur", onBlur);
}
}
The on blur method is getting sent to the page.
Answer:
I believe that Page.ClientScript has been deprecated. You should be using ClientScriptManager.
Replace your "?????" with the name of the script. Honestly, the name of the script is almost useless (unless you need to check for its existence later on).
ClientScriptManager.RegisterStartupScript(this.GetType(), "myCount", getCounter);
Usage Clarification:
//You must surround your code with script tags when not passing the bool param
ClientScriptManager.RegisterStartupScript(this.GetType(),
"myCount",
"<script>alert('Hey')</script>");
// The last param tells .Net to surround your
// code with script tags (true) or not (false)
ClientScriptManager.RegisterStartupScript(this.GetType(),
"myCount",
"alert('Hey')", true);
Additional Information:
Signatures from MSDN:
public void RegisterStartupScript(
Type type,
string key,
string script
)
public void RegisterStartupScript(
Type type,
string key,
string script,
bool addScriptTags
)
See: http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx
I think you need to use the ClientScriptManager.RegisterClientScriptBlock method
Try this
EDITED:
var getCounter = "<script language=\"javascript\">" +
"function GetCounter(input) {" +
//this function gets the number of special characters taht are in a row.
//it is only the grouping of characters that are right after your current position
"var textbox = document.getElementById(input.id);" +
"var mask = textbox.getAttribute('Mask');" +
"var inputCharacters = textbox.getAttribute('InputCharacters');" +
"var tbid = \"#\" + input.id;" +
"var position = $(tbid).caret().start;" +
"var counter = 0;" +
"for (var i = position; i < mask.length; i++) {" +
" if (mask[i] != '#') {" +
" counter++;" +
" if (mask[i + 1] == '#') {" +
" break;" +
" }" +
" }" +
"}" +
"return counter;" +
" }" +
"</script>";
this.TextBox1.Attributes.Add("OnFocus", "GetCounter(this);");
if (!ClientScript.IsClientScriptBlockRegistered("getCounter")) {
ClientScript.RegisterClientScriptBlock(this.GetType(), "getCounter", getCounter, false);
}
You would put the actual function definition, which you already have in getCounter. Note that the second parameter which you currently have as "????", as James pointed out, is for the script's key, which must be unique from all other scripts registered for this type. The third parameter is the script itself, and the fourth determines whether script tags are to be added, which needs to be false, since you already added them.
Page.ClientScript.RegisterStartupScript(this.GetType(),
"someKeyForThisType", getCounter, false);