How to get results from javascript in .NET - c#

after long surfing via google I hope somebody can give good answer.
Here I have some javascript with I get in .NET C#
<script type="text/javascript">
var itemMap = new Array();
itemMap[0] = {
pid: "20466846",
sku: 13897265,
sDesc: "XSMALL",
sId: "101979",
cDesc: "Black",
cId: "1203740",
avail: "IN_STOCK",
price: "$4.99",
jdaStyle: "60016655"
};
How can I get results from this string in .NET that I can work with it?
I tried to use JINT (http://jint.codeplex.com/) but when I run script it's return for me type of object and I can not do anything with that...
I need with out some changes in javascript source get data. It's not JSON obj so I can not parse it.
Any suggestions?
Thanks

If you have an appropriately formed JSON object stored in the clip board (which I'm guessing is the transport that you'll be using to send to your back-end), you can create an object via Paste Special under the edit menu that will generate the appropriate class in .NET to hold that object, e.g.
This also works for XML objects.

You can save these values into hidden fields
<script type="text/javascript">
var hiddenField1 = document.getElementById('hiddenField1');
hiddenField1.value = ???;
</script>
<asp:HiddenField runat="server" ID="hiddenField1" Value="" ClientIDMode="Static" />
and in codebehind file you can access the hidden field by
hiddenField1.Value;

Related

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

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]%>';

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.

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

Explicitly define control prefix in ASP.NET 1.1?

I've got some (badly written) legacy code that I have to modify but I'm having an odd problem with the prefixing of the controls.
The main page has several include files, including cpct_cost.aspx.
Within that included page is a control EquipmentCost:
<INPUT id="EquipmentCost" type="text" name="EquipmentCost" runat="server" size="10" onchange="TotalCost();" class="bk">
Another page references that control in client side javascript:
function TotalCost()
{
var a = document.CPCT_FORM.cpct_cost_EquipmentCost.value;
This is throwing a client error because when I run the code locally, the control is being named with a $ instead of an _:
<input name="cpct_cost$EquipmentCost" type="text" id="cpct_cost_EquipmentCost" size="10" onchange="TotalCost();" class="bk" />
And as a result, the client side javascript can't find the element in question.
The legacy code on the server handles this differently - the control name there is processed as:
<input name="cpct_cost:EquipmentCost" id="cpct_cost_EquipmentCost" type="text" size="10" onchange="TotalCost();" class="bk" />
and this is being processed correctly.
I thought at first it might be a local IIS setting, so I compiled my code and deployed it to the dev server, but the behavior was identical to my local execution.
I'm using what are supposed to be the latest source files, I haven't changed any project settings, so ... is there some way I can force the code from my machine to use the : instead of $? Or ... what am I missing?
The project is currently on the proposal list to be completely rearchitected, (so please, no suggestions to redesign the app ;) ) but in the mean time, I have a short term requirement to implement some minor new functionality in this ugly old beast, and I've got to get it done ASAP. What's frustrating is - I haven't changed these parts of the code at all, but the behavior is changing anyway.
UPDATE
Apparently the naming prefix used in at least .NET 1.1 is somewhat random, because after several builds, while I was trying various ways to work around this, the controls ended up getting the right name. So now I'm just not changing the code, which sucks because I really hate taking this "freeze it while it's randomly right" approach.
You could pass in a reference to the input control as a parameter to the JS function, ie:
<INPUT id="EquipmentCost" type="text" name="EquipmentCost" runat="server" size="10" onchange="TotalCost(this);" class="bk">
function TotalCost(txtEquipCost) {
var a = txtEquipCost.value;
}
Then it doesn't matter what the id is.
EDIT:
If you have more controls, create JS variables on the page, eg:
var txtEquipCost = document.getElementById('<%= YourControl.ClientID %>');
var txtOtherCost = document.getElementById('<%= YourOtherControl.ClientID %>');
Then the onChange function call could be TotalCost(txtEquipCost, txtOtherCost)
EDIT2:
See this question about ClientId and UniqueId which may be useful:
C# asp.net Why is there a difference between ClientID and UniqueID?
You could change your Javascript to use the id that is getting generated.
function TotalCost()
{
var a = document.getElementById('<%= YourControl.ClientID %>').value;
}
Also if you need absolute control over the generated id of that control it turns out that in asp.net 4.0 the ClientIDMode property was introduced so that developers have more control over how that id is generated.
Check out these two sources
http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientid.aspx
http://weblogs.asp.net/asptest/archive/2009/01/06/asp-net-4-0-clientid-overview.aspx

JavaScript Error: conditional compilation is turned off in MVC2 View

I am trying to call a JavaScript function on click in a MVC2 View Page.
<a onclick=" SelectBenefit(<%=o.ba_Object_id %>,<%=o.ba_Object_Code %>)" href="#">Select</a>
JavaScript function
function SelectBenefit(id,code) {
alert(id);
alert(code);
}
Here ba_Object_Id and Code are the values from the ViewModel. If I use SelectBenefit(<%=o.ba_Object_id %>) in this way, its working fine. But when I have two paramaters its not.I am getting this error:
conditional compilation is turned off.
I think that you need to put quotes around the second parameter if it is a string:
<a onclick=" SelectBenefit(<%=o.ba_Object_id %>, '<%=o.ba_Object_Code %>')" href="#">Select</a>
This being said your parameters need to be properly encoded and I wouldn't pass them likse this. I would serialize them as JSON object to ensure that everything is OK. Like this:
<a onclick="SelectBenefit(<%= new JavaScriptSerializer().Serialize(new { id = o.ba_Object_id, code = o.ba_Object_Code }) %>)" href="#">Select</a>
and then the SelectBenefit function might look like this:
function SelectBenefit(benefit) {
alert(benefit.id);
alert(benefit.code);
}
I'm guessing o.ba_Object_Code is not a number? Try putting quotes around it:
<a onclick="SelectBenefit(<%=o.ba_Object_id %>,'<%=o.ba_Object_Code %>')" href="#">Select</a>
You could also write this function like this:
Select
Or use Jquery (best approach, imo):
$('#yourlinkid').click(function(){
SelectBenefit(<%=o.ba_Object_id %>,'<%=o.ba_Object_Code %>');
return false;
});

Categories