Javascript var inside a c# function inside Javascript - c#

I am trying to write a javascript function that calls an Dictionary value and than tries to split it on a ยด_'. The problem is that the Key to get the value from Dictionary is in an Javascript var that is extracted from a dropdownlist. Is it possible to use an Javascript var inside an c# function inside Javascript?
the Code as it is now:
var Category = document.getElementById('Properties').value;
var Name = document.getElementById(Category).value;
Category = '#Model.Dictionary[Name].Split('_')[0]';
EDIT:
People are misinterpreting my problem, the .Split function does work but the Dictionary[Name] is giving me problems. if i enter
var Category = document.getElementById('Properties').value;
var Name = document.getElementById(Category).value;
Category = '#Model.Dictionary["Bicycle"].Split('_')[0]';
into the code it works perfectly, but I want to get the "Bicycle" part dynamically out of an DropDownList.
EDIT 2:
Okay I have decided that what I am over thinking the situation and that what I am trying to do needs alot more work than is needed, found a beter solutions, thanks for everybody that tried to help me.

You're a bit mixed up between client and server side. To interact with server side code like this, you'll need to either post to the server or write an AJAX callback to call a server method.
http://mikehadlow.blogspot.com/2008/10/mvc-framework-and-jquery-ajax-heaven.html

No, that is not possible. All the server code runs before the page is sent to the browser, and all the client code runs after.
What you would have to do to use the dictionary in the client code is to create Javascript code from the server side, that recreates the dictionary on the client side.
If that's not possible, you would have to make an AJAX call to the server.

I have avoided the issue completely by having the DropDownList have different values in Value and Text, doing this is can get the wanted input that used to be in the Dictionary out of the Value of the DropDownList without changing the Text.

Related

Error when trying to create/update a custom form

I've been assigned to work on a project that uses the AtTask API to create an issue and accompanying custom form from a web application I've built for our intranet. I've been using this post, ATTask API - Updating Custom Field with API and C Sharp, as my main starting reference for accomplishing my task.
Like that post, I'm also getting (500) Internal Server Error, though the error I receive the URL is inserted directly into the browser is {"error":{"class":"com.attask.util.json.JSONException","message":"org.codehaus.jackson.JsonParseException: Unexpected character ('S' (code 83)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')\n at [Source: java.io.StringReader#45c828e1; line: 1, column: 6]"}}.
My URL looks like this:
https://myCo.attasksandbox.com/attask/api/v3.0/optask?method=put&projectID=myID&name=API%20SandBox%20Issue&updates={DE:Service%20Affected:Electronic%20Communications,DE:Technical%20Details:I%20dunno,DE:How%20will%20this%20change%20be%20communicated?:It%20wont}&username=myUserName&password=myPassword
I have noticed that one difference between the post I reference above and my URL is that the other post's URL is looking for a categoryID. Is that necessary for working with Custom Forms? If so, where do I find that ID? (I did a search query on an issue that had custom form of the kind I'm trying to generate, but no categoryID was returned).
By the way, my search query looks like this:
Console.WriteLine("**Searching for Change Management Issues");
JToken cmIssues = client.Search(ObjCode.ISSUE, new
{
projectID=cmProjID,
name="SandBox Issue",
name_Mod="contains",
fields="parameterValues"
});
foreach (JToken issue in cmIssues["data"].Children())
{
Console.WriteLine(issue["name"]);
Console.WriteLine(issue["categoryID"]);
Console.WriteLine(issue);
}
I've used both ISSUE & OPTASK ObjCode types, with no luck on the categoryID.
Try removing the sessionID. At the end you are using your username & password, you do not need both. Make sure you spell password correctly. In your example you spelled it wrong.
If that does not work. Make sure all the spaces are replaced with %20 by UrlEncode it before you send the call.
After finally being able to come back to this project, I found that my problems lay with my unfamiliarity with JSON calls. For this particular issue, (after the I fixed the spelling of password), I was receiving my error because I had surrounded neither the custom form object I was sending nor the related value in quotation marks.
Basically, my problem was that I was doing this:
DE:The Object:The Value
when I should have been doing this:
"DE:The Object":"The Value"

Get data from server side variables in a JS variable?

I want to store data in a client side variable from a server side one, is it a good practice?
I have an app which uses a web service and I dont want to expose the ip on the source code, so it would be good if I can set a client side variable with that ip.
Now someone told me that for example getting values from the Session and storing them in a JS variable could be known as a "bad thing", as it represents an XSS Hole and I dont want my website to be marked as a "unsafe" one.
The reason I want to store the value on a client side variable is so that I can use JQUERY - AJAX so that the client does not have to re load the page for every request.
Can you help me out?
There's nothing inherently wrong with saving server side data on the client side.
Here's an easy way, for PHP:
<script>var someValue = "<?php echo $some_value; ?>";</script>
This saves a PHP value in the someValue JavaScript variable.
For more complicated data structures, here's a nice way to convert between the two languages:
<script>var someValue = JSON.decode("<?php echo json_encode($some_value); ?>");</script>
This only becomes a bad idea when the data you want to save client side is sensitive. There's no way to tell what your intentions are, so you have to use your best judgment.
Code Generating in JS
<script >
<%= SomeMethodFromCodeBehind() %> //JS goes here.
</script >
Pros: You get access to everything you want on the server.
Cons: You are writing JS using C# and C# string methods aren't exactly templating engine.
You will think you have access to Session, but only at code gen time!
If you mix user input into the results, then this is "JavaScript Injection", which get's lumped in with XSS.
Code Generating Just the Data
<script >
var myNumber = parseInt(<%= Convert.ToInt32(Session["TheNumber"]) %>,10);
var id = '<% TextBox.ClientID %>';
</script >
The above just generates the data, not all the code, so it's easier to see what is potential user input (maybe the Session part) and then force it to a suitable datatype, or do some JS escaping on the strings.
In my experience, I've only needed to ever do this for ClientIDs and sometimes properties of controls that don't have a clientside API.
Calling Services
If you don't code generate function that returns 42, maybe you can leave the function on the server and just have the JS gather the parameters. For one, calling a webservice isn't going to be subject to XSS-- the user would have to attack the parameters of the webservice, where as in code generation, the user can do all sorts of attacks if only he can figure out how to get his code output (esp on someone elses browser). So now you get to create a JS friendly web API. Here are some things that can go wrong:
<script >
//Things that used to be somewhat secret are potentially public now.
PageMethods.GetSesion("Blah",onSuccess);
//Wow, something that used to be hard for the user to tamper with is now convenient to
//tamper with. Now Session is ALL user input (and hence evil)
PageMethods.SetSession("Blah",42);
//Okay, now the user has the ability to read your secrets, conveniently
PageMethods.Encrypt("Blah", onSuccess);
PageMethods.Decrypt("Blah", onSuccess);
if(password=="xyzzy")
{
PageMethods.ShipTheGoods(address,goods); //User can call this directly.
}
</script >
(I'm not promoting PageMethods, but they sure are shorter for sample code than the alternatives)
The above sort of code is another common issue when you write JS code when you're used to writing server side code. One book called this overly granular APIs and attacks on control of flow (that if statement that doesn't really protect ShipTheGoods from being called without a password)
Anyhow, in a JS page, the way to track state (i.e. Session) is just a variable, "var customerInFocus = 'joe'). You can use code generation to output a value-- then when you are ready to save, send it back to the server in a pagemethod (or web service) call and treat all of those parameters as user input that has possibly, probably been tampered with along the way.

adding razor statement in javascript

Im trying to add some C# code in my javascript. But I can't parse my var name into the C# code.
What I want is this:
$.ready(function(){
var name = $("#input");
#Class.text(name)
});
But it wont allow me to parse the name.
This is a short version of what i got, the #Class represent a more complex function
The syntax is indeed incorrect.
The var name = $("#input"); is javascript. It is executed at the client end after the document is loaded. The #Class is server side and is executed when the page is being generated.
You cannot use javascript variables in C#. What is it that you are trying to achieve; there may be a different way to do so.
--
Update : You are trying to call a c# method from javascript.
Overall this will require a post back to the server - see http://blog.bobcravens.com/2009/11/ajax-calls-to-asp-net-mvc-action-methods-using-jquery/
#MichaelTotKorsgaard Based on our discussion in the comments of your question, I think I now understand. Unfortunately what you're trying to do simply won't work. It doesn't work that way. The reason you do AJAX/JSON is because, once C#/MVC/ASP.NET returns HTML (it doesn't actually know if what it returns is valid), it's up to the Client to "do stuff" with it. That's where Javascript comes in. But the server-side MVC and client-side JS don't actually know anything about each other. You Need to either 1) post back or 2) use AJAX.
It's time to saddle up and learn how to do it :)
If you give more details about what you're actually trying to accomplish -- like what you're trying to load from JS/AJAX -- then I'm sure SO can give you more information to set you on the right path.

jquery datatables fnfilter + script performace

I am away from my development workstation so I thought I'd ask this in hopes of getting an answer when I try it tomorrow. I have a two part question relating to a web application i built using c# jquery and jquery datatables:
1) I know that we can set the value of fnfilter as metioned on their page using something like:
var oTable;
$(document).ready(function() {
oTable = $('#example').dataTable();
/* Filter immediately */
oTable.fnFilter( 'test string' );
} );
however is there a way to retrieve the value entered by the use in the search bar? I was thinking along the lines of
var aContainer= oTable.fnFilter()
or
var aContainer= oTable.fnFilter($(this).html())
2) My application has to retrieve values from another source on the web. These are the value displayed in the datatable. Most of my processing(counting, etc..) is done client side and has drastically slowed down generating the web app. Does anyone know of any suggestions to increase performance of client side scripts specifically datatables?
If your datatable is really instantiated as oTable = $('#example').dataTable(); then doing this:
var textEntered = $('#example_filter input:text')[0].value;
Should return whatever the user entered on the field for filtering.
In answer to #1, you can get the value of the text entered into the search box by doing
// Assume the table's id attribute is 'blah'
var search_string = $('#blah_filter>input').val();
As far as #2, have you considered server-side processing of the data and sending the result to the client?
This article
might give you a big help if you decide to write server side code. Now researching it myself (and not looking forward to implementing custom filtering!).

How to get object in C# when it is dynamically created by javascript

I created several input text in Javascript in my .aspx
for (var i = 0; i < listbox.options.length; i++) {
var text = listbox.options[i].value;
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", "text");
element.setAttribute("value", text);
element.setAttribute("id", "TMruleItem");
element.setAttribute("style", "width:480px; margin-top:10px");
element.setAttribute("disabled", "disabled");
element.setAttribute("runat","server");
var foo = document.getElementById("Panel_TM");
foo.appendChild(element);
}
However, when I try to get the text of this object in C#(code behind the .aspx), it seems impossible. Can anybody help with this? Thanks a lot!
The js runs client side AFTER the C# (server side) has rendered the page.
You cannot do what you want because you have fundamentally flawed model of how these technologies interact.
Having said that; you could implement a web service or ajax framework to pass the text value to the server.
I'm not exactly sure how you will add this into the C# side of things (which live on the server), because this element is only being added to the clientside (even if you add an attribute runat="server"), because the page that was generated has been sent.
However, if you need to be able to add elements dynamically, you could always pass some information using an ajax call (etc) that is stored somewhere (a database) that is then read to re-create the html element next time the page is generated...
End result though is that for the C# to be able to access the element, it must exist at some point on the server. If instead of accessing the element, you just want to access the value, provided the form is posted (ajax or regular) the value will be part of the Request variables:
string value = Request.Params["TMruleItem"];
Add the following to your javascript code:
element.setAttribute("name", "TMruleItem");
and entered values will be available on the server side:
string value = Request.Form["TMruleItem"];
I think you'd need to add the element to the form and when you post back to the server you can pull the value out using Request.Form

Categories