I know you cant save javascript variables into server side variables (vbscript) directly, but is there a way around this like saving java script variables into html hidden inputs then using javascript to post. Is this possible? If not what else can i do? Below is my code so far get the value of a drop down list - javascript
function selectedDatabase() {
select_temp = form1.elements["selection"];
select_index = select_temp.selectedIndex;
select_text = select_temp.options[select_index].text;
}
Below is the HTML code
<center><select id="selection" onchange="selectedDatabase()">
<option>Movies</option>
<option>Movies 2</option>
<option>New Movies</option>
<option>New Movies 2</option>
</select></center>
</td></tr>
What you're looking for is called ajax. You can do it manually, or better use a JavaScript library such as MooTools, jQuery, or Prototype.
Check out Google University's Ajax tutorial. I would avoid w3schools' tutorials.
Just to cover all the bases, why can't you just have the user submit the form?
Also, you could do this with cookies, though you won't get the cookie values on the server until the next GET or POST from the user.
It is Possible to store javascript variable values into server side variable. All you have to do is to implement "System.Web.UI.ICallbackEventHandler" class.
Below is the code demonstrating how to do it.
In aspx Page:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Client Calback Example</title>
<script type="text/ecmascript">
function LookUpStock()
{
var lb=document.getElementById("tbxPassword");
var product=lb.value;
CallServer(product,"");
}
function ReceiveServerData(rValue){
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="password" id="tbxPassword" />
<input type="Button" onclick="LookUpStock">Submit</button>
</div>
</form>
</body>
**
In Code Behind (CS) Page
**
public partial class _Default : System.Web.UI.Page,System.Web.UI.ICallbackEventHandler
{
protected String returnValue;
protected void Page_Load(object sender, EventArgs e)
{
String cbReference = Page.ClientScript.GetCallbackEventReference
(this,"arg", "ReceiveServerData", "context");
String callbackScript;
callbackScript = "function CallServer(arg, context)" +
"{ " + cbReference + ";}";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
"CallServer", callbackScript, true);
}
public void RaiseCallbackEvent(String eventArgument)
{
if(eventArgument == null)
{
returnValue = "-1";
}
else
{
returnValue = eventArgument;
}
}
public String GetCallbackResult()
{
return returnValue;
}
}
Now you can get the JavaScript variable "product" value into Server side variable "returnValue".
Related
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
I am trying to use a c# variable to remove an attribute.
I am testing my approach before actually coding application.
I've tried javascript and jQuery but found nothing that would allow to
substitute TextBox ID with value of string in codebehind.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="WebApplication2.index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="myText" runat="server" required="required"></asp:TextBox>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication2
{
public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string straspID = "myText";
bool fieldRequired = false;
if (fieldRequired == false)
{
//FindControl("myText");
FindControl(straspID);
if (straspID != null)
//
myText.Attributes.Remove("required");
// I want to use straspID instead of the ID of the asp page
// which will returned from a table - I'm simulating here
// I get an error if I use straspID for remove attribute
}
}
}
}
My expected result is to remove the attribute for selected ID.
I am currently getting a syntax error.
This
FindControl(straspID);
is not doing what you think it is.
Can you check your index.aspx.designer.cs file and see if there is a protected member variable called 'myText' ?
If there is, you can simply do this: -
if (fieldRequired == false)
{
myText.Attributes.Remove("required");
}
If there is no protected member called myText, add one at class level to 'index': -
namespace WebApplication2
{
public partial class index : System.Web.UI.Page
{
protected Textbox myText;
(etc)
As long as you declare it of the correct type and with the same name and casing, there is no need to resort to FindControl to access a server control.
private void loadform(List providerList)
{
foreach (ProviderInRequest req in providerList)
{
// taget div for plan
Control ctrl = FindControl("div" + req.aspName);
// set visible to true if we found it.
if (ctrl != null)
{
//set div to visible
ctrl.Visible = true;
// set label to proper text
Label lbl = (Label)Page.FindControl("lbl" + req.aspName);
lbl.Text = displayName;
I've been trying to isolate the mail feature from 2sxc mobius app to implement it on my own 2sxc projects, but so far I've only been successful on passing string, string dictionary. If I try to use the default string,object it gives several compiling not very specific errors.
Here's what I have working right now:
View:
<div>
<div>
<label for="testfield">Test field</label>
</div>
<div>
<input type="text" id="testfield" value="">
</div>
</div>
<div>
<button id="saveData" type="button" onclick="saveMailData()">Guardar dados</button>
</div>
<script type="text/javascript" src="/desktopmodules/tosic_sexycontent/js/2sxc.api.min.js" data-enableoptimizations="100"></script>
<script>
function saveMailData() {
var newItem = {
"user": "#Dnn.User.Username",
"testfield": $("#testfield").val()
};
$2sxc(#Dnn.Module.ModuleID).webApi.post("Form/ProcessForm", {}, newItem, true)
.success(function() {
alert("Success");
})
.error(function() {
alert("Error");
});
}
</script>
Controller:
using DotNetNuke.Security;
using DotNetNuke.Web.Api;
using System.Web.Http;
using ToSic.SexyContent.WebApi;
using System.Collections.Generic;
using System;
using System.Linq;
using System.Web.Compilation;
using System.Runtime.CompilerServices;
using DotNetNuke.Services.Mail;
using Newtonsoft.Json;
public class FormController : SxcApiController
{
[HttpPost]
[DnnModuleAuthorize(AccessLevel = SecurityAccessLevel.Anonymous)]
[ValidateAntiForgeryToken]
public void ProcessForm([FromBody]Dictionary<string,string> contactFormRequest)
{
string mailFrom = "x#x.pt";
string mailTo = "y#y.com";
string mailCc = "z#z.com";
string mailReply = "w#w.pt";
string mailSubject = "THIS IS THE SUBJECT " + contactFormRequest["user"].ToString();
string mailbody = "<table><tr><td>THIS IS THE MESSAGE BODY</td></tr></table>";
var ownerMailEngine = TemplateInstance("testmailtemplate.cshtml");
var ownerBody = ownerMailEngine.Message(contactFormRequest, this).ToString();
var ownerSubj = ownerMailEngine.Subject(contactFormRequest, this);
Mail.SendMail(mailFrom, mailTo, mailCc, "", mailReply, MailPriority.Normal, ownerSubj, MailFormat.Html, System.Text.Encoding.UTF8, ownerBody, new string[0], "", "", "", "", false);
}
private dynamic TemplateInstance(string fileName)
{
var compiledType = BuildManager.GetCompiledType(System.IO.Path.Combine("~", App.Path, fileName));
object objectValue = null;
if (compiledType != null)
{
objectValue = RuntimeHelpers.GetObjectValue(Activator.CreateInstance(compiledType));
return ((dynamic)objectValue);
}
throw new Exception("Error while creating mail template instance.");
}
}
And template:
#helper Message(Dictionary<string,string> request, ToSic.SexyContent.IAppAndDataHelpers context)
{
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
body { font-family: Helvetica, sans-serif; }
</style>
</head>
<body>
<h1>Website contact form request</h1>
<p>Key/Value:</p>
<table width="100%">
#foreach (var item in request)
{
<tr>
<td width="10%"><b>#item.Key.ToString()</b></td>
<td>#item.Value.ToString()</td>
</tr>
}
</table>
</body>
</html>
}
#functions {
public string Subject(dynamic request, dynamic helpers) {
return "this is a subject from template";
}
}
I would really like to avoid using dynamic to receive data (it's a nightmare for beginners), so can you help me to properly pass data as objects (string,object) from JS to controller and from controller to razor template?
If you try to use you'll somehow assume that the system will correctly convert these to number, date and so forth. This will usually not be reliable and cause a lot of side-effects. For example, a number from an input-field would be a string in the browser, so it would also arrive as a string in the server.
Dates would be worse: they would be treated as strings - and no automatic detection would turn them into dates, because the JSON format used by AJAX-calls has no standard for dates.
So basically both numbers and dates would give you no benefit if you tried an object approach (as it wouldn't automatically have the other type). So I'm not sure if there is any additional benefit. Is there another reason to do this?
Good day!
I need a help on activating my javascript function via on-load on code behind.
Here is my code:
string script = #"var applyCss = function () {
var css = '#CalendarPanel1-month-day-20170607, #CalendarPanel1-month-day-20170614 {background-color: #D0D3D4;}';
Ext.net.ResourceMgr.registerCssClass('someCssClassId', css);
}; ";
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "css", script, true);
By the way, my code above works in front-end via button click.
But my desired result is, I want my javascript function to work on page load without needing to click the button. I put my javascript function in code-behind because I will put dynamic dates in the css variables. The code above still has static variables. (CalendarPanel1-month-day-20170607)
Will gladly appreaciate any response / solution. Big thanks!
You could use an immediately invoked function to do the trick. Basically you don't give a name to your javascript function and you invoke it right after it's defined.
For example:
var script = #"(function () {alert('Hello');})(); ";
ScriptManager.RegisterStartupScript(this, typeof(Page), "123", script, true);
You need to wrap the function with its body between parenthesis then another set of parenthesis to invoke the function.
You can also pass parameters to your function (which I'm assuming it's what you want to do):
var myAlertText = "Hello Hello";
var script = #"(function (myText) {alert(myText);})('" + myAlertText + "');" ;
If I were you though I would defined the function in client code and just invoke it from code behind with the right parameters.
An alternative and fancier way to call javascript code from code behind would be using X.Call(). Check out this example:
<%# Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!X.IsAjaxRequest)
{
string script = #"var myJSSideVar = 'my var value';
var applyCss = function (paramOne, paramTwo) {
var css = '#CalendarPanel1-month-day-20170607, #CalendarPanel1-month-day-20170614 {background-color: #D0D3D4;}';
Ext.net.ResourceMgr.registerCssClass('someCssClassId', css);
Ext.Msg.alert('applyCss called.', 'I\'ve been run with parameters: (' + paramOne + ', ' + paramTwo + ').');
};";
var hi = "hello";
X.AddScript(script);
X.Call("applyCss", new object[] { hi, new JRawValue("myJSSideVar") });
}
}
</script>
<html>
<head runat="server">
<title></title>
</head>
<body>
<form runat="server" id="form1">
<div>
<ext:ResourceManager runat="server" />
</div>
</form>
</body>
</html>
Notice the second parameter sent to the script call is sent "raw", i.e., it calls: applyCss("hello", myJSSideVar)
If you need to pass but one single parameter you don't need to pass an array, e.g. X.Call("applyCss", hi);
I am using an external javascript file for my asp.net project. Now i want to get the session value in that javascript. How can i get the session value in that javascript file?
Thanks in advance..
<script>
var someSession = '<%= Session["SessionName"].ToString() %>';
alert(someSession)
</script>
This code you can write in Aspx. If you want this in some js.file, you have two ways:
Make aspx file which writes complete JS code, and set source of this file as Script src
Make handler, to process JS file as aspx.
You can access your session variable like '<%= Session["VariableName"]%>'
the text in single quotes will give session value.
1)
<script>
var session ='<%= Session["VariableName"]%>'
</script>
2) you can take a hidden field and assign value at server;
hiddenfield.value= session["xyz"].tostring();
//and in script you access the hiddenfield like
alert(document.getElementbyId("hiddenfield").value);
For me this code worked in JavaScript like a charm!
<%= session.getAttribute("variableName")%>
hope it helps...
I tried following with ASP.NET MVC 5, its works for me
var sessionData = "#Session["SessionName"]";
protected void Page_Load(object sender, EventArgs e)
{
Session["MyTest"] = "abcd";
String csname = "OnSubmitScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the OnSubmit statement is already registered.
if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
{
string cstext = " document.getElementById(\"TextBox1\").value = getMyvalSession() ; ";
cs.RegisterOnSubmitStatement(cstype, csname, cstext);
}
if (TextBox1.Text.Equals("")) { }
else {
Session["MyTest"] = TextBox1.Text;
}
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script language=javascript type="text/javascript">
function getMyvalSession() {
var txt = "efgh";
var ff = '<%=Session["MyTest"] %>' + txt;
return ff ;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack=true ></asp:TextBox>
<input type="submit" value="Submit" />
</div>
</form>
</body>
</html>
If you are using VB as code behind, you have to use bracket "()" instead of square bracket "[]".
Example for VB:
<script type="text/javascript">
var accesslevel = '<%= Session("accesslevel").ToString().ToLower() %>';
</script>
var sessionVal = '#Session["EnergyUnit"]';
alert(sessionVal);