I have following code .
In asp.net , I set session variable .Then pass it to javascript for modification .
In javascript I can read session variable value and return modified value in TextBox1 .
In asp.net again , I receive modified session variable value and store it in session variable .
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>
But my aim was –
Within javascript function itself I should be able to modify session variable .
And I don’t want to use submit button.
Using cookie i can preserve value . Submit button is also not required . So this code has solved my purpose .
<script language="javascript" type="text/javascript">
function writeCookie(name,value,days) {
var date, expires;
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires=" + date.toGMTString();
}else{
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var i, c, ca, nameEQ = name + "=";
ca = document.cookie.split(';');
for (i = 0; i < ca.length; i++)
{
c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1,c.length);
}
if (c.indexOf(nameEQ) == 0) {
return c.substring(nameEQ.length,c.length);
}
}
return '';
}
function restore(){
var sId = readCookie('sessionId');
document.getElementById("TextBox1").value = sId ;
}
function backup() {
var sId = document.getElementById("TextBox1").value;
writeCookie('sessionId', sId, 3);
}
function getMyvalSession() {
var ff = "Loading Value";
return ff;
}
function TextBox1_TextChanged() {
backup();
}
</script>
<body onload="restore()">
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" Name="TextBox1" runat="server"
AutoPostBack="True" onchange="TextBox1_TextChanged()" ></asp:TextBox>
</div>
</form>
</body>
protected void Page_Load(object sender, EventArgs e)
{
Loading();
}
void Loading (){
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);
}
}
No, session variables cannot be modified on client side directly and expect to change on server. Atleast, AJAX request has to be made to persist the session value.
And based on your current code, I am not understanding significance of session variable. You're just appending text box value with session variable and submitting the form.
So, it would be direct statement without needing client side script, i.e,
//page_load
{
Session["Mytest"] = test;
}
//page_submit
{
Session["Mytest"] += txtName.text;
}
You can define a web method in asp.net or action in MVC and set session inside it from parameter passed
[HttpPost]
public bool SetSessionAction(string param)
{
Session[sessionName] = param;
return true;
}
then call method or action using $.ajax or $.post from jquery.
var paramValue = 'some data';
var targetUrl = "#Url.Action("SetSessionAction", "ControllerName" )";
$.ajax({
type: "POST",
cache: false,
dataType: "json",
url: targetUrl,
data: { param: paramValue },
success: function (s) {
alert('Set Session is: ' + s);
}
});
Good Luck
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) ; }
So I'm trying to do some input validation on an ASP form and if the validation fails it's not supposed to try and submit the form but simply show a modal window (bootstrap) with the error and then let the user fix the error/fill in the blanks they forgot.
But whenever I press my HTML button (or ASP button I've tried both) it shows the modal window and does a postback right after. I can see that this happens because I have to upload fields that lose their file references and I have a dynamically created dropdown which also resets.
I would like to find a way to get around this but after looking at several SO answers I havne't found a solution.
Using the popular return false; solution makes the submit button stop working all together.
My HTML:
<div class="row">
<script>
function activityAdd() {
__doPostBack('Activity_Add', 'postback');
};
</script>
<asp:Button CssClass="btn btn-success" Style="font-size: 20px;" runat="server" OnClientClick="activityAdd();" Text="Submit"/>
<a class="btn btn-danger" runat="server" href="~/Index" style="font-size: 20px;">Cancel</a>
</div>
C# Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, typeof(Page), "CreateDepartmentDropdown", "$(document).ready(function(){CreateDepartmentDropdown(" + GetDepartmentDropdownList() + ");});", true);
ScriptManager.RegisterStartupScript(this, typeof(Page), "RegisterDatepickers", "$(document).ready(function(){RegisterDatepickers();});", true);
//Activity_Add.Attributes.Add("onClick", "return false;");
//Activity_Add.Click += Activity_Submit_Click;
if (Request["__EVENTARGUMENT"] == "postback")
{
SubmitActivity();
}
}
And the Submit Method:
public bool SubmitActivity()
{
bool InputValidated = true;
List<String> ErrorMessages = new List<String>();
int fye = Int32.Parse(fye_dropdown.Value);
String activityName = activity_name_field.Value;
String[] ax_accounts = (ax_account_numbers_field.Value.Contains(',') ? ax_account_numbers_field.Value.Split(',') : new String[1] { ax_account_numbers_field.Value });
if (activityName.Length == 0)
{
InputValidated = false;
ErrorMessages.Add("The Activity Name is not filled.");
}
String activity_responsible = responsible_field.Value;
int department;
if (department_dropdown_selected_value.Value.Length == 0)
{
department = 0;
}
else
{
department = Int32.Parse(department_dropdown_selected_value.Value);
}
DateTime start;
DateTime end;
// Since the dates are formatted for Americans we will rearrange day and month in code.
// Otherwise the JavaScript that checks the two Calendars break and we can't parse a DateTime object.
try
{
String[] date = datepicker_start.Value.Split('/');
String parseString = date[1] + "/" + date[0] + "/" + date[2] + " 00:00:00 AM";
start = DateTime.Parse(parseString);
}
catch (Exception)
{
InputValidated = false;
ErrorMessages.Add("The Start Date was not formatted right. Please only click in the box and choose a date from the calendar.");
}
try
{
String[] date = datepicker_start.Value.Split('/');
String parseString = date[1] + "/" + date[0] + "/" + date[2] + " 00:00:00 AM";
end = DateTime.Parse(parseString);
}
catch (Exception)
{
InputValidated = false;
ErrorMessages.Add("The End Date was not formatted right. Please only click in the box and choose a date from the calendar.");
}
if (ax_accounts[0].Length == 0)
{
InputValidated = false;
ErrorMessages.Add("You need to add at least one AX Account for the Activity.");
}
if (!description_upload.HasFile)
{
InputValidated = false;
ErrorMessages.Add("Please choose a file to upload for the Detailed Description of the Activity");
}
if (!estimation_upload.HasFile)
{
InputValidated = false;
ErrorMessages.Add("Please choose a file to upload for the Estimation of the Activity.");
}
if (InputValidated == false)
{
StringBuilder sb = new StringBuilder();
sb.Append("An Error happened while submitting the activity. Please see below for details.");
sb.Append("<br>");
foreach (String msg in ErrorMessages)
{
sb.Append("- ").Append(msg).Append("<br>");
}
String jsExec = Util.ModalAlert(sb.ToString(), "#error_modal", ".modal-body");
ScriptManager.RegisterStartupScript(Page, GetType(), "error_modal_show", jsExec, false);
return false;
}
else
{
byte[] descriptionBytes = description_upload.FileBytes;
String descriptionFileName = description_upload.FileName;
byte[] estimationBytes = estimation_upload.FileBytes;
String estimationFileName = estimation_upload.FileName;
String msg = Util.Alert("Success");
Response.Write(msg);
return true;
}
}
But that doesn't work as expected either. All the fields mentioned earlier still reset. It's infuriating me to no end because it's going to be a frustrating experience for the user. Any idea on how to approach this problem?
How can I retrieve value from javascript function in codebehind, on page load ..
javascript function like :
<script type="text/javascript">
function isIFrame() {
var isInIFrame = (top.location != self.location);
if (isInIFrame) {
return "inside";
}
else {
return "outside";
}
}
</script>
and code behind like :
protected void Page_Load(object sender, EventArgs e)
{
string resutOfExecuteJavaScript = "";
// resutOfExecuteJavaScript = isIFrame(); // from javascript
if (resutOfExecuteJavaScript == "inside")
{
// do something
}
else
{
// do something
}
}
thank you.
You cannot directly call a client side javascript method from server side code . For that first you need to assign the function result to value of some hidden variable and then access it in server side
Suppose you have an hidden field like this
<input type="hidden" runat="server" id="hdnVal"/>
then you can set the value as below
document.getElementById("hdnVal").value=isIFrame();
then at serve side
string resutOfExecuteJavaScript = hdnVal.Value;
using _doPostBack, you can solve this one
<script type="text/javascript">
function isIFrame() {
var isInIFrame =(top.location != self.location);
var result;
if (isInIFrame) {
result="inside";
}
else
{
result ="outside";
}
__doPostBack('callPostBack', result);
</script>
</head>
In code behind section
protected void Page_Load(object sender, EventArgs e)
{
this.ClientScript.GetPostBackEventReference(this, "arg");
if (IsPostBack)
{
string eventTarget = this.Request["__EVENTTARGET"];
string eventArgument = this.Request["__EVENTARGUMENT"];
if (eventTarget != String.Empty && eventTarget == "callPostBack")
{
if (eventArgument == "inside"){
//do something
}
else if(eventArgument == "outside")
{
//do something
}
}
else
{
// set the button click
btnclick.Attributes.Add("onClick", "isIFrame();");
}
}
Below link will help you out to get more idea.
http://www.dotnetcurry.com/ShowArticle.aspx?ID=203
in javascript file or your script add :
function SetHiddenVariable()
{
document.getElementById(inpHide).value= "value";
}
in .aspx add this tag:
<input id="inpHide" type="hidden" runat="server" />
in aspx.cs (c# file) add :
anyVariable = inpHide.Value;
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 hidden variable in my .aspx page.
input type="hidden" runat="server" id="isdup"
Now in code behind i check for certain conditions and assign isdup a value accordingly. However, this may not help you much but this is what i do in code behind.
bool exist = (from n in mCDC.NCDCPoints
where n.EVENT_TYPE_ID == eventID
where n.BeginDate == begin
where n.EndDate == end
select n).Count() > 0;
try
{
if (!exist)
{
//do this before insert so the insert will have correct values
isdup.Value = "false";
SaveAllColumnFields(ref ncdc, e);
mCDC.NCDCPoints.InsertOnSubmit(ncdc);
mCDC.SubmitChanges();
//do this after insert because it wont work until the ncdc object
//has been assigned an ID
SaveAllDynamicFields(mCDC, ref ncdc, e);
mCDC.SubmitChanges();
Grid1.CurrentPageIndex = 0;
}
else
{
isdup.Value = "true";
System.Windows.Forms.MessageBox.Show(isdup.Value);
}
Now I need to access the isdup inside javascript. However the problem has been that those values are not passed and isdup is null.
var showus= document.getElementById("<%=isdup.ClientID %>").value;
alert(showus);
if(showus == "true")
{
Showduplicate();
}
So, kindly let me know the mistake i have been doing?
Hve you tried with:
var showus= document.getElementById('<%=isdup.ClientID %>').value;
update
is javascript at the end of the page?
update
try to put this code in the page:
<asp:HiddenField ID="isdup" runat="server" Value="eee"/>
<script>
var showus = document.getElementById("<%=isdup.ClientID %>").value;
alert(showus);
</script>
this works for me!
update
in page_load...
protected void Page_Load(object sender, EventArgs e)
{
if (!ClientScript.IsStartupScriptRegistered("clientscript"))
{
string script1 = "<script language=JavaScript>";
script1 += "var showus= document.getElementById('" + isdup.ClientID + "').value;";
script1 += "alert(showus);";
script1 += "</script>";
ClientScript.RegisterStartupScript(typeof(Page), "clientscript", script1);
}
my example:
protected void pagesTree_NodeClick(object sender, RadTreeNodeEventArgs e)
{
PageStructure page = pageService.GetPage(Guid.Parse(e.Node.Value));
this.LoadPageData(page);
isdup.Value = "xxx";
}
update
bool exist = (from n in mCDC.NCDCPoints
where n.EVENT_TYPE_ID == eventID
where n.BeginDate == begin
where n.EndDate == end
select n).Count() > 0;
if (!ClientScript.IsStartupScriptRegistered("clientscript"))
{
string script1 = "<script language=JavaScript>";
script1 += "var showus= document.getElementById('" + isdup.ClientID + "').value;";
script1 += "alert(showus);";
script1 += "</script>";
ClientScript.RegisterStartupScript(typeof(Page), "clientscript", script1);
}
try
{
if (!exist)
{
//do this before insert so the insert will have correct values
isdup.Value = "false";
SaveAllColumnFields(ref ncdc, e);
mCDC.NCDCPoints.InsertOnSubmit(ncdc);
mCDC.SubmitChanges();
//do this after insert because it wont work until the ncdc object
//has been assigned an ID
SaveAllDynamicFields(mCDC, ref ncdc, e);
mCDC.SubmitChanges();
Grid1.CurrentPageIndex = 0;
}
else
{
isdup.Value = "true";
System.Windows.Forms.MessageBox.Show(isdup.Value);
}
Try this JQuery code.
var showus= $("#<%=isdup.ClientID %>").val();
Replace your input field and try this with jquery code
UPDATED
<asp:HiddenField ID="isdup" runat="server" EnableViewState="true" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"/>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
var showus = $("#<%=isdup.ClientID %>").val();
alert(showus);
if (showus == "true") {
Showduplicate();
}
});
</script>