Getting session variables from c# to a different aspx page? - c#

I am trying to get strings that I have put in my session variables to another aspx webform. I am getting it inside my JS script and I would like to know how to go about it. I have tried the following but it doesnt seem to work. Please anyone guide me a bit.
Home.aspx.cs
HttpContext.Current.Session["InstitutionID"] = BankID;
HttpContext.Current.Session["InstitutionName"] = txtBankName.Text.Trim();
Index.aspx
$(document).ready(function () {
var param1var ='<%= Session["InstitutionID"]%>';
var param2var = '<%= Session["InstitutionName"]%>';
console.log('param1', param1var);
console.log('param1', param2var);
........
})

Are you using System.Web.SessionState.HttpSessionState.Session object to get the session object data in the Javascript? That is how I use it in one of my WebForms projects. Hope it helps.
HttpContext.Current.Session[Constants.SessionStateVariables.LoginFailed] = false;
var loginIsFailed = '<%=Session[XYZProcet.Common.Constants.SessionStateVariables.LoginFailed]%>';

Related

How to insert a header on SharePoint page

I have a very simple requirement but of course as is the case with CSOM it seems really difficult to achieve anything. I did have a solution for this, but now that the site template has changed (outside of my control) nothing works any more, and I have no idea how to debug this.
Requirement
Add a simple header to an existing SharePoint page.
Old solution
This used to work great. I pass in the page name, the web part xml and the details of the zone (I have no idea how I found those it seems ridiculously complicated just to insert a web part with code... why?...)
When i try it now I get
the object specified does not belong to a list
On the 2nd ExecuteQuery()
private void InsertWebPart(ClientContext clientContext, string webPartXml, string markerTemplate,
string pagePath, string zoneId, int zoneIndex, string description, string content, string fieldName)
{
var relUrl = new Uri(baseUrl).AbsolutePath;
clientContext.Credentials = credentials;
var web = clientContext.Web;
var page = clientContext.Web.GetFileByServerRelativeUrl($"{relUrl}/{pagePath}");
var webPartManager = page.GetLimitedWebPartManager(PersonalizationScope.Shared);
var importedWebPart = webPartManager.ImportWebPart(webPartXml);
var webPart = webPartManager.AddWebPart(importedWebPart.WebPart, zoneId, zoneIndex);
clientContext.Load(webPart);
clientContext.ExecuteQuery();
var marker = string.Format(markerTemplate, webPart.Id);
var item = page.ListItemAllFields;
clientContext.Load(item);
clientContext.ExecuteQuery();
item[fieldName] = marker + item[fieldName];
item.Update();
clientContext.ExecuteQuery();
}
I tried this solution but all I get is
the object specified does not belong to a list
Again... Please can someone advise?
How hard can it be to just simply add 1 header?
Check the solution below:
1.You can add "?contents=1" in the current site page, and remove the custom web part which add it using the CSOM code.
2.Open the site page using SharePoint designer, and edit in Advanced Mode.
3.Add the Header HTML code and JavaScript code under the "PlaceHolderMain" control.
Example code:
<div id="customHeader" style="height:20px;width:auto;background-color:green">Test</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function () {
$("#ms-designer-ribbon").before($("#customHeader"));
});
</script>
4.Save the page.
If you can't use the SharePoint designer, we can also use script editor web part/content editor web part with some HTML code to achieve it.
If you want to make all the page have the custom header, we can add some code into the master page to make it works.

How to get the variable from aspx to aspx.cs [C#] [duplicate]

This question already has answers here:
Pass javascript variable to Codebehind
(2 answers)
Closed 7 years ago.
I'm developing a small app and I have a question about posting variables between WebPage.aspx and WebPage.aspx.cs .
I've got the variable from WebPage.aspx.cs to WebPage.aspx like this:
WebPage.aspx.cs code:
public string AdresKlienta = string.Empty;
public string AdresPizzerii = string.Empty;
WebPage.aspx code:
var origin2 = '<%= AdresPizzerii %>';
var destinationA = '<% = AdresKlienta %>';
On WebPage.aspx I use javascript function that contains variables that I use do some work and I create another variable that I would like to post back (WebPage.aspx -> WebPage.aspx.cs).
I've been searching on the Internet for the solution, but found nothing. I'll appreciate any help.
Posting back a variable simply involves putting it in a form element somewhere. So let's say you create a form element:
<input type="hidden" name="someElement" id="someElement" />
Then in your JavaScript code you would set the value of that element:
document.getElementById('someElement').value = someValue;
When the form containing that element posts to a server-side resource, that resource can then access that value:
var someValue = Request.Form["someElement"];
The point is that in order for server-side code to receive any values from client-side code, those values need to be included in a request to the server of some kind. Whether it's a form POST, a query string value on a GET request (from a redirect or clicking a link), an AJAX request in the background, etc. The client-side code needs to make a new request to the server-side code in order to send it that value.
You can use hidden field, using javascript you can enter a value to this field and can be accessed from your code behind also.

MVC javascript redirect page not working

In MVC, the default views for a controller allow one to reach the edit page via selecting an item in an index and using that id to reach the specific edit page.
In this MVC edit page, I have a javascript that reacts to a change in a dropdown. The dropdown represents a subset of the potential id's available from the index page, and in general, someone will choose a different one than the currently displayed one.
The postback to the control works correctly in C#, and I can find the relevant model that goes with the id. It all appears correct on the C# controller side. However, when I try to get it to redirect back to the same edit page but with a different id (that from the dropdown), the page reverts back to the ajax call.
Is there anyway to "short-circuit" the ajax call so that it "knows" that it doesn't return but lets the C# redirect to the edit page (just like what happens when an element is chosen from the index page).
Thanks in advance,
Joseph Doggie
If you are making ajax requet, then you have to implement a way to redirect.
Depends on your ajax protocol... Are you returning json? html ...
If returning json, you could add a flag in your response telling wether this is a redirect answer and do redirect in js :
window.location = url
OK, there is at least one way to do this.
Assume editing X with Controller named YController:
JavaScript:
var MyControllerUrlSettings = {
MyControllerPrepareModifyXInfoUrl: '#Url.Action("PrepareModifyAssetInfo", "Y", new { x_txt = "param" })'
}
one then has a JavaScript to handle the dropdown change:
$('#ModelXList').change(function () {
//// alert('Change detected');
if ($("#ModelXList").val() != "") {
//// alert('Reached here');
var XNbrString = $("#ModelXList").val();
var trimmedXNbrString = $.trim(XNbrString);
//// debugger;
if (trimmedXNbrString != "") {
var url = MyControllerUrlSettings.MyControllerPrepareXInfoUrl;
window.location.href = url.replace('__param__', trimmedXNbrString);
}
}
else {
}
});
Finally, in the controller, there is a method:
public ActionResult PrepareModifyXInfo(string XNbr_txt)
{
// we cannot save anything here to cdll_cdcloanerlist;
// static variables must be used instead.
/// .... do what you have to do....
return RedirectToAction("ModifyEdit", new { XNbr_txt = XNbr_txt });
}
Note: For proprietary reasons, I changed some of the syntax so that everything would be general, therefore, you may have to work with the above code a little, but it works
Alternate answers are really welcome, also!

How can i Get a Another Form Session Value in Java Script File Using ASP.Net?

am having Sample.aspx and sample.js both are in different directory.
how can i get the Sample.aspx page session values in sample.js file ?
i cant get the value for the following types
function session() {
alert('<%=Session.getAttribute("hdn_CheckedData")%>');
alert(document.getElementbyId("hdn_CheckedData").value);
alert('<%=Session["CheckedData"]%>');
alert('<%=Session("CheckedData")%>');
alert('<%=Session["CheckedData"].ToString()%>');
alert('<%=Session("CheckedData").ToString()%>');
};
CheckedData - is the session
hdn_CheckedData - is the hiddenfield
i tried both of it.
is it possible then help me pls.....
Hiddenfiled, session, viewstate or anything............
One simple solution is to declare the session variables just before the load of your javascript file and inside the aspx page. Eg on sample.aspx you have
<script>
var sessionCheckData = "<%=session["CheckedData"].ToString()%>";
</script>
<script type="text/javascript" src="sample.js"></script>
and on sample.js you have
function session() {
alert(sessionCheckData);
};
Similar answer: How to get asp.net client id at external javascript file
You can save the session data to a hidden field on your page. After that you have direct access to that field in you js file.
Or you can declare a session variable as Aristos has proposed. That would more straightforward actually.
I would write a generic handler and use JSONP to pass any data to external Javascript.
Please take a look at here, here and here.
Since it is not cross domain, JSON should also work.
You have to assign session values to hiddenfield
after that you can use that values

Retrieve within Cookies from C# to jquery

Hello guys I have this problem of getting lastGuestInsertedId from C# cookies in a code behind file to another web form that retrieve lastGuestInsertedId values by jquery and then show the value by alerting. Any ideas?
C# codes
HttpCookie GuestCookie = new HttpCookie("GuestCookie");
GuestCookie["Key"] = Convert.ToString(lastGuestInsertedId) ;
GuestCookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(GuestCookie);
JQuery codes
var guestkey = $.cookie("GuestCookie")
alert(guestkey);
$.cookie is not part of default jQuery. You need some jQuery plugin to do that.
To check if you actually have cookies on client side - alert(document.cookie).

Categories