putting model variables inside js code - javascript

i have issues alternating js and razor syntax.
i am trying to pass the value of a model variable to a javascript function, let's say something like this
<script>
//this is my javascript function setTitle that simply changes the title
of a modal window, and i want to pass to it the title from the model
...
setTitle(#Model.titleName);
...
</script>
so when i do this it doesn't work, and the script seems to break.

If it's a string you have to surround it with quotes.
setTitle('#Model.titleName');
If it's an integer you obviously don't need that.
In situations like these it's helpful to Right Click -> View Source, and take a look at the javascript it generated, and also report any errors the console window showed when asking a question.

You need to encase the Razor code in quotes so the result is a JavaScript string
setTitle("#Model.titleName");

Related

jQuery string escape onclick='deleteRow(item"+count+")' how to quote around item and count

I don't even know how to ask this question correctly, I tried to put quotes around a part of my string however it always break.
I am creating html dynamically and I am encountering error when I try to do this:
onclick='deleteRow("item"+count+"")'
I am trying to pass item1 as a string to a deleteRow function however best I could do is pass it like this deleteRow(item1) with no quotes. I am not sure how to escape them so that they would show.
This line of code is generated inside my JavaScript file.
I would recommend to use jQuery event handlers instead of inline one..
But in this case the below should do it
"onclick='deleteRow(\"item"+count + "\")'"

Pass variable to a javascript function in a c# code

I need to pass a variable to a javascript function,but I got a little trouble.
In the .cs file,I write like this:
string id = "someid";
this.Controls.Add(new LiteralControl("<input type=\"button\" onClick=\"myFunction("+id+")\">"));
I need to use the value of this id,but in the console.log(id),it just shows "object",not the "someid",what's the problem?
Look at the generated HTML:
<input type="button" onClick="myFunction(someid)">
You are generating a variable name when you want a string literal.
Add some quote marks.
Whenever you have a problem that manifests in the browser: Look at the code the browser is dealing with first. You should always start by determining if the JS you want is not working or if the server side code is not generating the JS you want.
just add '' around id as i did below will resolve your issue
this.Controls.Add(new LiteralControl("<input type=\"button\" onClick=\"myFunction('"+id+"')\">"));
Use the single quotes around id:
'"+id+"' (notice the single quotes then double quotes)
The problem is that it is looking for a saved variable on the page named someid, which is why you are getting the object in the console. Pranay Rana has a good solution which is to make sure the string someid is surrounded by single quotes.

Trying to call a function in javascript

This is my code all I need to do is call a function which will write the contents to a dynamic div
<script language='javascript' type='text/javascript'>
function getComments(id)
{
alert(id);
}
var resultSet="";
function CreateDiv()
{
resultSet+="<br/><div id='"+rows.data[i].id+"'></div><script language='javascript' type='text/javascript'> getComments("+rows.data[i].id+"); <\/script>";
}
window.onload=CreateDiv;
</script>
The function getComments is not being called at all
What's that I am missing here
There are a few problems there.
You're referencing rows without defining it anywhere, which will cause an exception.
Assuming you define rows somewhere you haven't shown, the code's just creating a string containing a script tag and putting that string in resultSet. To cause the code inside the script tag to run, you'd have to assign resultSet to innerHTML on some element.
There's an extra ) in your call to getComments within the generated script.
Separately: Your id values would appear to be numbers (this is based on your passing them into getComments with no quotes around them). Note that using id values starting with a digit is allowed in HTML5, but not in earlier versions of HTML and not in CSS, so it's probably best avoided.
There's almost certainly a better way to do what you're actually trying to do, you may consider a separate question outlining the goal, how you've approached it so far, and asking for alternatives.
I would suggest that you break the code down into steps while you debug it. Specifically where you populate resultSet. Break it down at each plus sign. Then you can step through it and see how it is being populated.
resultSet+="<br/><div id='";
resultSet+=rows.data[i].id;
and so on.
Secondly, have a look in View Source to see what this looks like on the page when you run it. Does the HTML look properly formed?
Also, I am questioning whether that final <\/script> in resultSet is correct.
Try replacing the createDiv function with this:
function CreateDiv(){
resultSet += "<br/><div id='"+rows.data[i].id+"'></div>" + getComments(rows.data[i].id);
}
It should work flawlessly.

JQuery Templates - Use string as data

I am using jQuery templates to create a message dialog. The only data that needs passed is a message which is a string. The problem I face and have not seen documented is how I should reference the message data in my template when it is not wrapped in an object:
$.tmpl('messageAlertTmpl', message).appendTo(dialog);
With this I can't reference the data as ${message} because message is the outer object, so the property is undefined.
All examples I have seen just use properties of an object to reference the data within the template, which would cause me to have to do something like this:
$.tmpl('messageAlertTmpl', { message: message }).appendTo(dialog);
I was thinking that $value may work like it does with {{each}} however this does not seem to be the case.
Is this possible?
I think you can use $data but I'm working on a jsfiddle to be sure :-)
edit yes that works though it's a little ugly — inside the template string, ${$data} will expand to the value of the whole "data" object. Thus:
$.tmpl("Hello ${$data}", "world").appendTo("#x");
will append "Hello world" to element "x".
$data is a reference to the current data object (which is the message in your case). That should work.

ASP.NET inline server tags

I'd like to start by saying that my code is working perfectly, this is more a "how best to do it" kind of question.
So I have code like this in my .aspx file:
function EditRelationship() {
var projects=<%= GetProjectsForEditRelationship() %>;
// fill in the projects list
$('#erProjectsSelect').empty();
for(var i in projects)
$('#erProjectsSelect').append('<option value='+projects[i][0]+'>'+projects[i][1]+'</option>');
var rels=<%= GetRelationshipsForEditRelationship() %>;
// etc
}
Again, it's working fine. The problem is that VS2008 kinda chokes on code like this, it's underlining the < character in the tags (with associated warnings), then refusing to provide code completion for the rest of the javascript. It's also refusing to format my document anymore, giving parsing errors. The last part is my worst annoyance.
I could put some of these in evals I guess, but it seems sorta dumb to add additional layers and runtime performance hits just to shut VS up, and it's not always an option (I can't remember off the top of my head where this wasn't an option but trust me I had a weird construct).
So my question is, how do you best write this (where best means fewest VS complaints)? Neither eval nor ajax calls fit this imo.
If your aim is to reduce VS complaints, and if you are running asp.net 4 (supporting Static client Ids), maybe a strategy like the following would be better?
Create a ASP:HiddenField control, set its ClientIdMode to "Static"
Assign the value of GetRelationshipsForEditRelationship() to this field on page load
In your javascript, read the value from the hidden field instead, I assume you know how to do this.
It's more work than your solution, and you will add some data to the postback (if you perform any) but it won't cause any VS complaints I guess :)
You could do this from your page in the code-behind
ClientScript.RegisterArrayDeclaration("projects", "1, 2, 3, 4");
or to construct something like JSON you could write it out
ClientScript.RegisterClientScriptBlock(GetType(), "JSONDeclarations", "your json stuff");
UPDATE Based on my comment
<script id="declaration" type="text/javascript">
var projects=<%= GetProjectsForEditRelationship() %>;
var rels=<%= GetRelationshipsForEditRelationship() %>;
</script>
<script type="text/javascript">
function EditRelationship() {
// fill in the projects list
$('#erProjectsSelect').empty();
for(var i in projects)
$('#erProjectsSelect').append('<option value='+projects[i][0]+'>'+projects[i][1]+'</option>');
}
</script>
I don't have VS2008 installed to test with, so take this with a grain of salt, but have you tried something like this?
var projects = (<%= GetProjectsForEditRelationship() %>);
Something like that might trick the JavaScript parser into ignoring the content of your expression.
For what it's worth, VS2010 correctly parses and highlights your original code snippet.
Is it an option to move this to VS2010? I just copied and pasted your code and the IDE interpreted it correctly.
The best solution is to put javascript in a separate file and avoid this entirely. For this particular function, you're doing server-side work. Why not build the list of options that you intend to add dynamically in codebehind, put them in a hidden div, and then just have jQuery add them from the already-rendered HTML?
If you have a situation where you really want to dynamically create a lot javascript this way, consider using ScriptManager in codebehind to set up the variables you'll need as scripts and register them, then your inline script won't need to escape
ScriptManager.RegisterClientScript("projects = " + GetProductsForEditRelationship());
(Basically, that is not the complete syntax, which is context dependent). Then refer to "projects" in your function.
(edit)
A little cleaner way to do this on a larger scale, set up everything you need like this in codebehind:
string script = "var servervars = {" +
"GetProductsForEditRelationship: " + GetProductsForEditRelationship() +
"GetRelationshipsForEditRelationship: " + GetRelationshipsForEditRelationship() +
"}"
and refer to everything like:
servervars.GetProductsForEditRelationship
If you do this a lot, of course, you can create a class to automate the construction of the script.

Categories

Resources