Jquery get property from C# has warning in visual studio 2012 - c#

I have a property in the aspx.cs page:
public string UtilizatorLogat
{
get
{
return (!(Session["utilizator"] == null)).ToString().ToLower();
}
}
And I get it in the aspx page, on $(document).ready:
utilizatorLogat = <%=UtilizatorLogat%>;
But visual studio says: Syntax Error.
I cannot include it in "" because it's a boolean value and I don't want to make it a string one...
Any ideas why is this warning shown?

It's a syntax error to the JavaScript parser, which doesn't think <%=UtilizatorLogat%> is valid. This is a common problem when mixing client/server code.
One way you can work around this is to quote the value, but then parse or test it (in JavaScript) to a boolean.
var utilizatorLogat = /true/i.test("<%=UtilizatorLogat%>");
When the page renders, it will be:
var utilizatorLogat = /true/i.test("false");
It looks strange, but this way you avoid syntax errors in the designer which can also cause problems with automatic formatting.

You need to convert it to string if you want to use it with on client side
var utilizatorLogat =<%=UtilizatorLogat.ToString().ToLower()%>;
You can use this trick too to avoid warnings:
original code:
<script type="Text/javascript">
<%If Page.IsPostback Then%>
alert("my javascript code");
<%End If%>
</script>
solution:
<script type="Text/javascript">
//<%If Page.IsPostback Then%>
alert("my javascript code");
//<%End If%>
</script>
Reference: Visual Studio confused by server code inside javascript

I think is a mix between Adriano and Phx answer (Adriano don't put the quotes)
I use always this kind of solution and it works
var utilizatorLogat ='<%=UtilizatorLogat.ToString().ToLower()%>';

Related

How do I inject javascript code via webview?

Basically what I want to do is this this but I can't seem to find something similar for webview XAML control. What I ultimately need to do, is capture an incoming json file from the webview. As is, I get a bad request from the server and unsupported file exception from the webview. I thought about injecting a javascript so that it would alert me, I could get the body of the incoming json and bypass all the errors.
There are two main things you can do:
Call functions programically
Inject any code by using the HTML string
Function Calling
You can use InvokeScript to call javascript functions.
If you have in a webpage with a script:
<script lang="en-us" type="text/javascript">
function myFunction() {
alert("I am an alert box!");
}
</script>
Then you can in C# call:
MyWebview.InvokeScript("myFunction", null);
Which will execute the script function myFunction.
Injecting Text
If you download the HTML page and all other needed files(using the Windows HttpClient), you can inject any code by manipulating and then Navigating to string.
Lets say you want to change the above script to add another function, "HelloWorld", then you can
Search the file for something you know will be there, such as: <script lang=\"en-us\" type=\"text/javascript\">
Using string manipulation, add the desired text, such as a function (but this can be anything)
Navigate to the String
The C# code:
string MyWebPageString = GetWebpageString(WebpageUri);
string ScriptTagString = "<script lang=\"en-us\" type=\"text/javascript\">";
int IndexOfScriptTag = MyWebPageString.IndexOf(ScriptTagString);
int LengthOfScriptTag = ScriptTagString.Length;
string InsertionScriptString = "function SayHelloWorld() { window.external.notify(\"Hello World!\");} ";
MyWebPageString = MyWebPageString.Insert(IndexOfScriptTag + LengthOfScriptTag + 1, InsertionScriptString);
MyWebview.NavigateToString(MyWebPageString);
The result will be that the navigated to Webpage will look like this:
<script lang="en-us" type="text/javascript"> function SayHelloWorld() { window.external.notify("Hello World!");}
function myFunction() {
alert("I am an alert box!");
}
</script>
Since the injection can be applied to any area, even the HTML, you should be able to figure something out.
Hope this helps. Good luck.
This answer was based on this MSDN blog

#Url.Action inside $.get

I've seen a few posts about this but stills couldn't understand why this is not working
$.get('#Url.Action("Edit","Contacts")', {id: parseInt($(this).attr('id')) } , function (result) {
obviously this does
$.get("/Contacts/Edit/" + parseInt($(this).attr('id')), function (result) {
I've tried with replacements and still getting the proper id but the #Url.Actions appears as a string itself generating weird routes as this one for the former code, seems to me that the url.action is not executed, right?
localhost:53720/#Url.Action(Edit,%20Contacts)?id=23918
Edition: Actually the route generated for that code is
localhost:53720/Url.Action(%22Edit%22,%20%22Contacts%22)?id=23918
the other is for another try I've made
Anyone can tell me why?
Thanks
To have access to HtmlHelpers inside javascript, the javascript code must be inside a View page, and not inside a javascript file
<script>
var url = '#Url.Action("Edit","Contacts")';
console.log(url);
</script>
Looks like #Url.Action is not getting called and the URL is not being returned.
var url = '#Url.Action("Edit","Contacts")';
$.get(url, {id: parseInt($(this).attr('id')) } , function (result)
If JS complains about the above, you can try specifying #: beforehand to let razor take control.

How to Get JavaScript value From c# back end

Hi guy i have a javasciprt will create a value , is that any way for me to capture the value in my c# back end code.
function GetKey(){ return Key; } //key is a combination value
Thank you
C# in backend
public String MyVariable;
MyVariable = "Some Value";
ASPX
<%=MyVariable %>
via ajax
You can put it into your aspx page code and pass it to your js (if you are using asp).
If Key is an object, you can serialize it to json string and use JSON parser to deserialize it. If it is a basic type, use <%= Key %> in your asp page is OK. (Note you cannot put the code in your js file)
<script type="text/javascript">
var key = JSON.parse('<%=JsonConvert.SerializeObject(someObj.GetKey()) %>');
//now you can use key in your js logic
</script>

PageMethods in ASP.NET failed to work if you have ASP.NET Routing Implemented

I have a web method:
[System.Web.Services.WebMethod]
public static string getCharacterstics(int product_id, int lang_id)
{
// code goes here...
}
I want to access it using PageMethods like:
(Provided the condition that i have Enable PageMethods in ScriptManager):
<script type="text/javascript">
$(document).ready(
function () {
$('#characterstics').html("loading");
// '<%= product_id_property %>' , '<%= this.LanguageID %>'
PageMethods.getCharacterstics(0 ,0 , OnSave);
}
);
function OnSave(result) {
}
</script>
I get the error "the http verb post to access path.. is not allowed"
I googled it and search the SO too but does not get any solution regarding to it Based on ASP.NET Routing.
What i believe is that because of asp.net routing the service methods are not accessible.
In addition i think i cannot even use JSON because of asp.net routing too.
Any help is appreciated.
Updated:
If i run the page with this url:
http://localhost:2606/searchdetail.aspx
The web method executed successfully.
Now
I have routing like this:
routes.MapPageRoute("searchdetail", "searchdetail/{ID}", "~/searchdetail.aspx");
routes.MapPageRoute("searchdetail", "searchdetail", "~/searchdetail.aspx");
The set_path() will work only for case 2 i.e without ID but does not work with case 1
if i try
http://localhost:2606/searchdetail
It works fine
but if i try to use:
http://localhost:2606/searchdetail/123
It gives error that object expected.
So set_path() is the option what should i write.
Currently, WebMethods don't work transparently with the Routing framework. There is a work around. You have to access the PageMethods directly by doing the following in your javascript:
PageMethods.set_path('/the/path/to/your/page.aspx');
PageMethods.YourMethod(params, onSuccess, onFailure);
I hope this helps.
I kept running into this myself. With routing enabled, if I added a value to the path, it would start to fail again. This solution is a bit of a hack, but it seems to be working consistently.
Create a server control hyperlink where the navigate url refers to itself, then once the control renders, grab the href and use it for set_path
This gets around the issue of set_path not referring to the correct location if you called
<asp:HyperLink ID="hlPage" runat="server" NavigateUrl="~/user.aspx" ClientIDMode="Static"></asp:HyperLink>
<script>
$(document).ready(function () {PageMethods.set_path($('#hlPage').attr('href'));})
</script>

How do I pass a list from aspx to javascript?

I have a list that I loop through to populate my table. I would like to pass a row of data to my javascript code at best. If not, I would like to pass the list and the id number to search for that row in the list. How can I do this?
<%foreach(var item in Model.NewList) { %>
<tr>
<td><%=item.EntryDate.ToShortDateString() %></td>
<td onmouseover="showDetailsHover(<%=item %>,<%=item.idNumber%>);"
onmouseout="hideDetailsHover();"><%=Html.ActionLink(item.idNumber,"SummaryRedirect/" + item.idNumber) %></td>
</tr>
<% } %>
You can use Json serialization to pass this data
http://json.codeplex.com/ - library for serialization
The concept of "passing a list from aspx to javascript" is a little hard to understand since your ASP.NET code runs on the server and javascript code runs in the browser. Because they exist in different domains, you can't simply "pass" a list from one domain to the other.
However, you have several options available:
Expose a web service that you can access from javascript. The web service can be responsible for providing the row of data so that javascript can understand it.
Put staticly formatted JSON data directly into your javascript function when your page loads. JSON is a format that javascript can understand. While technically this isn't "passing" a variable into a javascript function from ASP.NET, it is saying "Here's the data I want to run in my javascript function when/if it runs on the client."
The quickest way I can think of is this:
Use Json.Net to serialize your list as json string on your page.
Include jQuery and jQuery-json plugin.
Define a javascript list in a javascript function.
Something like this on your aspx page:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://jquery-json.googlecode.com/files/jquery.json-2.2.js"></script>
<script type="text/javascript">
function foo() {
// This is where we use the Json.Net library
var rawJsonString = '<%= Newtonsoft.Json.JsonConvert.SerializeObject(Model.NewList) %>';
// This is where we use the jQuery and jQuery-json plugin
var list = $.evalJSON(rawJsonString);
// Do stuff with your list here
}
</script>
THanks for the ideas. I eventually dug a little deeper with your suggestions and I used a for loop on the list I passed then add my data to the row based on the loop...
success: function(data) {
var loopList = data.message.NewList;
for (var i = 0; i < loopList.length; i++) {
addRecentData(loopList[i]);
}
},
});
function addRecentData(data) {
....
}
THanks for the nudge!

Categories