I am developing MVC application and using razor syntax.
I want to use HTML code in JavaScript in cshtml file, but I get confused about how to use double quotes in JavaScript in razor syntax. Is that matter?
This is line of code:
<span class="EmpName"> #Html.ActionLink(item.Owner.FullName, "Details", "EMployee", new { id = item.OwnerId }, new { #style = "color:#1A6690;" })</span>
#Html.DisplayFor(ModelItem => item.CommentDateTime)
<span class="EmpName"><button type="button" id = "#item.Id" class="deleteComment">Delete</button></span>
And I have written below code in JavaScript, is that right?
success: function (data) {
$("p.p12").append
("<div style=\"background-color:#FAFAFA\";>Recently Added... <br />" + data.OwnerName + ""
+ data.cmtDateTime + "<button type=\"button\" id = \" + data.Id + "\class=\"deleteComment\">Delete</button></span><br />" + data.msg + "</div>");
}
and I have written below code in JScript is that right ?
No, it doesn't seem right. The generated HTML is broken. You need to be more careful about the syntax, things liks spaces between the attributes and the quotes are important. Also you seem to be hardcoding urls instead of using url helpers. Try like this:
$('p.p12').append(
'<div style="background-color:#FAFAFA;">Recently Added... <br />' + data.OwnerName + '' + data.cmtDateTime + '<span><button type="button" id=' + data.Id + ' class="deleteComment">Delete</button></span><br />' + data.msg + '</div>'
);
or as I suggested you here which IMHO is more correct approach.
or since you are using an AJAX call, instead of returning JSON from your controller action, return a ParialView in which you will correctly build the markup using proper HTML helpers.
Like this:
[HttpPost]
public ActionResult SomeAction(SomeViewModel args)
{
MyViewModel model = ...
return PartislView("_SomePartial", model);
}
and then inside your strongly typed partial (_SomePartial.cshtml) build the markup without any string concatenations and spaghetti code mixing javascript and HTML:
#model MyViewModel
<div style="background-color:#FAFAFA;">
Recently Added...
<br />
#Html.ActionLink(Model.OwnerName, "Details", "Employee", new { id = Model.OwnerID }, null)
#HtmlDisplayFor(x => x.cmtDateTime)
<span>
<button type="button" id="#Model.Id" class="deleteComment">Delete</button>
</span>
<br />
#HtmlDisplayFor(x => x.msg)
</div>
Now all that's left in your AJAX success callback is to refresh the corresponding DOM section:
success: function(html) {
$('p.p12').append(html);
}
Related
I have used ajaxSubmit to upload file to linux server successfully. After upload file, name+size+delete should be appear in my website.
For example, 1.jpg、2.jpg、3.jpg were uploaded to server, my submit website shoule be appeared like:
1.jpg 3k delete
2.jpg 4k delete
3.jpg 5k delete
Before upload files, My html structure is :
<td style="width:30%" id="impPic">
<div class="btn">
<span>addFile</span>
<input id="fileupload" type="file" name="mypic">
</div>
<div class="files"><b>...</b><span>...</span></div>
</td>
After uploaded three files, I wanted html like:
<td style="width:30%" id="impPic">
<div class="btn">
<span>addFile</span>
<input id="fileupload" type="file" name="mypic">
</div>
<div class="files"><b>...</b><span>...</span></div>
<div class="files"><b>...</b><span>...</span></div>
<div class="files"><b>...</b><span>...</span></div>
</td>
My files has fixed css style:
.files{height:10px; font-size:10px;line-height:22px; margin:10px 0}
Here is my ajaxSubmit code:
var divD=1;
$(function () {
var files = $(".files");
newDiv = "<div class='files'+divD+''><b class='dataname'>'+data.name+'('+data.size+'k)</b> <span class='delimg' name='+data.name+'('+data.size+'k)' rel='+data.pic+'>delete</span></div>";
$("#fileupload").change(function(){
$("#myupload").ajaxSubmit({
dataType: 'json',
beforeSend: function() {
......
},
uploadProgress: function() {
},
success: function(data) {
$(newDiv).insertAfter($('#impPic div:eq('+divD+')'));
divD = divD + 1;
$('.files').html("<b class='dataname' >"+data.name+"("+data.size+"k)</b> <span class='delimg' rel='"+data.pic+"'>delete</span>");
},
error:function(xhr){
......
}
});
});
});
But unfortunately, it failed. I suppose files'+divD+'.html is wrong. Who can help me ?
I see two problem with your code...
First was the html string "newDiv" that you are trying to insert and the second is the invocation for jQuery .html() on an string literal object "files'+divD+'".
You are expecting the newDiv object to have a concatenated html string with the value of divD and the data came from the response but object data is undefined until the logic flows in the success callback.
and I believe the second problem would return a jquery TypeError problem, as you are trying to call the .html() function on a non DOM - jQuery object .
Update your code and try it this way:
newDiv = "";
...
success: function(data) {
newDiv = "<div class='files" + divD + "'><b class='dataname'>" + data.name + "(" + data.size + "k)</b><span class='delimg' name='" + data.name + data.size + "k' rel='" + data.pic + "'>delete</span></div>";
$(newDiv).insertAfter($('#impPic div:eq(' + divD + ')'));
divD = divD + 1;
$(".files" + divD).html("<b class='dataname'>" + data.name + "(" + data.size + "k)</b><span class='delimg' rel='" + data.pic + "'>delete</span>");
},
...
EDIT:
You can update the html string and add an Id to have a unique selector on each of the element with files class and instead of the above selector, change the class selector "." to an Id selector "#".
and your code will look like these...
newDiv = "<div id='files" + divD + "'class='files'"...
...
$("#files" + divD).html("<b class='dataname'>" + data.name + "(" + data.size + "k)</b><span class='delimg' rel='" + data.pic + "'>delete</span>");
If that doesn't suit your needs you can just leave the first example above and update your css selector to:
[class^='files'] instead of `.files`.
This will select all of the element with a class that begins with "files".
files'+divD+' is a string, and you try to call method html from string, which does not exist.
Try $('.files' + divD).html('something'); or files.find('.files' + divD).html('something');
I have written this small piece of razor code with java script:
#Html.ActionLink("ערוך", "Edit", new { id = item.tz }) |
#Html.ActionLink("הצג פרטים מלאים", "Details", new { tz = item.tz }) |
#{
var shem = ("האם אתה בטוח שברצונך למחוק את" + #Html.ValueFor(model => item.fname) + " " + #Html.ValueFor(model => item.lname) + "?");
#Html.ActionLink("מחק", "Delete", new { id = item.tz }, htmlAttributes: new { onclick = "return confirm('shem');"} )
}
All I want is for the variable to be displayed in the "return confirm," but for some reason it doesn't recognize that as a variable and will only write it down literally.
Things I've tried so far:
Putting the while variable in the "return confirm" and avoid using a variable completely.
Putting the name of the variable with an # in front of it.
removing the whole thing from the #{} (which caused the whole variable line to be rendered as a in the HTML page).
Removing the '' around the variable's name in the "return confirm."
So what am I doing wrong? I'm sure it'll end up being a small syntax thing, but I just can't figure it out...
Try like this:
onclick = "return confirm(" + Json.Encode(shem) + ");"
I am trying to pass a variable to the onClick function using a previously stored value. I have a database setup that searches for store locations when provided with a ZIP code. For example, the following link is generated using an ajax call after a user searches for a Zip Code. The returned value "WAFHOH3" is the ID that is associated with that particular store:
Generated Link:
<input type="button" onclick="myfunction(WAFHOH1);" value="This Is My Store" data-store-code="WAFHOH3">
Based on this code:
<div class="col-sm-3"><input type="button" onclick="myfunction(' + item.store_code + ');" value="This Is My Store" data-store-code="' + item.store_code + '"></div>
My problem is that if anything other than a number is returned I get a "Uncaught ReferenceError: WAFHOH3 is not defined" console error. When a number is passed like the example below, everything works fine and I get no errors and the application continues to work as expected.
For example (This Works):
Ive tried manually changing the character string to numbers only to isolate any database related issues. My only guess is that there is something in my code that is maybe attempting to verify the input as number.
The full code is below for the ajax call.
Full Code:
function myFunction() {
var searchValue = $('#foobar').val();
if (searchValue.length > 3) {
var acs_action = 'searchCction';
$.ajax({
async: false,
url: mysearchurl.url+'?action='+acs_action+'&term=' + searchValue,
type: 'POST',
data: {
name: searchValue
},
success: function (results) {
var data = $.parseJSON(results);
$('#resContainer').hide();
var html = '';
if (data.length > 0) {
html += '<br/><br/><ul>';
for (var i = 0; i < data.length; i++) {
var item = data[i];
html += '<li>';
html += '<div class="row myclass">';
html += '<div class="col-sm-9">';
html += ' <h3>' + item.label + '</h3>' ;
html += ' <span>' + item.desc + '</span>';
html += '</div>'
html += ' <div class="col-sm-3"><input type="button" onclick="dofunction(' + item.store_code + ');" value="This Is My Store" data-store-code="' + item.store_code + '"></div>';
html += '</div>';
html += '</li>';
}
html += '</ul><br/><br/><p>This is an example message please email us at admin#admin.com for assistance.';
}
else {
html += '<br/><br/><p>This is an example message, email us at admin#admin.com for assistance.';
}
$('#foo').html(html);
$('#foo').show();
$('.foobar').hide();
}
});
} else {
$('#foo').hide();
}
}
You need to wrap the input item.store_code with quotation marks; otherwise, it tries to treat it as a variable, not a string:
html += '<div class="col-sm-3"><input type="button" onclick="noActivationCodeRegistration(\'' + item.store_code + '\');" value="This Is My Store" data-store-code="' + item.store_code + '"></div>';
Ideally, you would attach a click handler after giving the buttons a class (such as register):
html += '<div class="col-sm-3"><input type="button" class="register" value="This Is My Store" data-store-code="' + item.store_code + '"></div>';
// Later
$('.register').on('click', function() {
var storeCode = $(this).data('storeCode');
noActivationCodeRegistration(storeCode);
});
I may be late, and maybe its an absolute mistake of me, but, i have to add my answer here because i just solved exactly the same situation in about three minutes ago .
I just solved this using the most simple sollution, and the error "Uncaught ReferenceError" from the console is solved, also i have my alert(); passing the variable as i needed.
I also need to include that i did not aproove the sollution gave, about "not using" the alert function, once i searched for the sollution, not for another method for that .
So, as i am using php, and the document is html, i thinked about the apostrophe charactere to the variable, after i had been spectating the element using chrome, first moving the function alert to the parent and child elements, that not solved .
After, also in the specting element, inside chrome F12 i tryed changing the function, including '' (that i passed in php code) into variable inside the alert function as: onclick="alert(variable);" to onclick="alert('variable');" and my alert had worked .
Ok. So, i try everything to insert '' 2 single quotes '' to my variable in php, that seems impossible, even if i change all my code to " and use ' or the oposite .
Then, i decided to try the most obvious and old school method, that is about charactere representation, and i cfound that ' (single quote) is represented by ' in php. Everything inside ->> ' <<-
My php code is like this : onclick="alert(''.$variable.'');"
It will work! (with no Vue), ok ? :)
I have a loop that creates links with a javascript function call in the onClick events and uses the text returned from a database as one of the parameters. My issues I am having is that sometimes this text being returned has parenthesis in them which is causing a syntax error in my code.
Example:
code:
formResults += "<a onclick='openForm(" + this.displayText + "," + this.ID + ");'>" + this.displayText + "</a>";
HTMLDisplay:
<a onclick="openForm(Example Form (Example Form 1) Application Instructions ,1108);">Example Form (Example Form 1) Application Instructions </a>
as you can see the name of the form contains a set of parenthesis. Is there anyway I can include these? The reason I need to is because the function points to another system that uses the ID and displayText in order to render the proper form.
thank you
The parenthesis aren't the problem, it's the lack of quotes inside the function.
formResults += "<a onclick='openForm(\'" + this.displayText + "," + this.ID + "\');'>" + this.displayText + "</a>";
This below snippet (from yours)
`openForm(Example Form...`)
Will throw an error because it's looking for variables Example and so on, quote that string!
I strongly suggest
code:
formResults += '<a class="openForm" data-text="'+this.displayText + '" id="'+this.ID + '">' + this.displayText + '</a>';
HTMLDisplay:
<a class="openForm" data-text="Example Form (Example Form 1) Application Instructions" id="1108">Example Form (Example Form 1) Application Instructions </a>
jQuery:
$(function() {
$(".openForm").on("click",function(e) {
e.preventDefault();
openForm($(this).data("text"),this.id);
});
});
I'm building a small app with a few modal dialog windows. The windows require a tiny bit of HTML. I've hard coded the window HTML in the javascript library but am not thrilled with this solution. Is there a more elegant way to do this? It seems that JavaScript doesn't have multi line strings/heredoc syntax.
var html = "<div id='email_window'><h2>Email Share</h2><div>";
html = html + "<form action='javascript:emailDone();' method='post'>";
html = html + "<div><label for='to'>To</label><input id='to' type='text'></div>";
html = html + "<div><label for='from'>From</label><input id='from' type='text' value='" + email + "'></div>";
html = html + "<div><label for='subject'>Subject</label><input id='subject' type='text' disabled='disabled' value='" + subject + "'></div>";
html = html + "<div><label for='body'>Body</label><input id='body' type='text' disabled='disabled' value='" + body + "'></div>";
html = html + "<div><input type='submit' value='Send'><input type='button' value='Cancel' onClick='javascript:$.fancybox.close();'></div>";
html = html + "</form></div>";
$("#data").html(html);
Added to clarify the original message-
Any solution can't use Ajax/XHR to pull in the template file because the javascript library will be on a different domain that the html file it's included in
It's a little like ShareThis. The library will be included on a number of different sites and attached to the onClick event of any anchor tag inside divs with attribute sharetool="true".
For example:
http://www.bar.com - index.html
<html>
...
<script type="text/javascript" src="http://www.foo.com/sharetool.js"></script>
...
<body>
<div sharetool="true">
</div>
...
</html>
You can include the HTML as regular markup at the end of the page, inside an invisible div. Then you're able to reference it with jQuery.
You then need to programmatically set your variable fields (email, subject, body)
<div id='container' style='display: none;'>
<div id='your-dialog-box-contents'>
...
...
</div>
</div>
<script type='text/javascript'>
$("#from").val(from);
$("#subject").val(subject);
$("#body").val(body);
$("#data").html($("#your-dialog-box-contents"));
</script>
Templates. Pick your poison
EJS
jQuery templates (nb: development discontinued)
underscore templates
mustache
jResig micro templates
Either inline them as script blocks or load them using ajax as external resources.
I personally use EJS as external template files and just get EJS to load them and inject them into a container with json data bound to the template.
new EJS({
url: "url/to/view"
}).update('html_container_name', {
"foobar": "Suprise"
});
And then view files use generic view logic.
// url/to/view
<p> <%=foobar %></p>
For multiline strings (no frameworks, just javascript) there are several solutions. See my answer to this SO Question. You could combine that with some simple templating:
String.prototype.template = String.prototype.template ||
function (){
var args = Array.prototype.slice.call(arguments)
,str = this
,i=0
;
function replacer(a){
var aa = parseInt(a.substr(1),10)-1;
return args[aa];
}
return str.replace(/(\$\d+)/gm,replacer)
};
//basic usage:
'some #1'.template('string'); //=> some string
//your 'html' could look like:
var html =
[ '<form action="javascript:emailDone();" method="post">',
' <div><label for="to">To</label>',
' <input id="to" type="text"></div>',
' <div><label for="from">From</label>',
' <input id="from" type="text" ',
' value="$0"></div>',
' <div><label for="subject">Subject</label>',
' <input id="subject" type="text" disabled="disabled" ',
' value="$1"></div>',
' <div><label for="body">Body</label>',
' <input id="body" type="text" disabled="disabled" ',
' value="$2"></div>',
' <div><input type="submit" value="Send"><input type="button" ',
' value="Cancel" ',
' onClick="javascript:$.fancybox.close();"></div>',
'</form>'
] .join('').template(email, subject, body);
Personally I like building DOM trees like this:
$('#data').html(
$('<div/>', {
id: 'email_window',
html: $('<h2/>', {
html: 'Email Share'
})
}).after(
$('<form/>', {
action: 'javascript:emailDone();',
method: 'post',
html: $('<div/>', {
html: $('<label/>', {
for: 'to',
html: 'To'
}).after($('<input/>', {
id: 'to',
type: 'text'
}))
}).after(
... etc
)
})
)
);
There is 2 solutions tto your problem:
- An alternative to the heredoc Syntax in javascript is to escape the newline char with \ :
var tpl = "hello\
stackoverflow\
World !";
The char is escaped so ignored, and it wont take place in the resulting string.
You can also create a plain html file with your template, and in your js script you create a hidden iframe and load the crossdomain html template. You can now access the document object of the iframe and retreive body.innerHTML. In theory! I Didn't tested this solution yet....
You're right, JS doesn't have heredocs or multi-line strings. That said, the usual approach to this is to have the HTML in...the HTML, and show or hide it as appropriate. You're already using jQuery, so you're most of the way there:
<div style="display:none;">
<form method='post' class="email">
<input id='from' type='text'> <!-- other form fields omitted for brevity -->
</form>
<form method='post' class="facebook"></form> <!-- again, omitted for brevity -->
</div>
Then, you can populate the form and toss it in the right spot:
$('#data').html($('form.email').find('input#from').val(email).end().html());
Cook.js
div([
button({click:[firstEvent, secondEvent]},
'You can bind (attach) events on the fly.'),
p('Here are some popular search engines'),
ul([
li([
a('Google', {href:'http://www.google.com'})
]),
li([
a('Bing', {href:'http://www.bing.com'})
]),
li([
a('Yahoo', {href:'http://www.yahoo.com'})
])
])
]);
how it works
Objects = Attribute & Events
-> {href:'facebook.com', src:'static/cat.gif', ng-bind:'blah'}
String = Text or Html
-> 'hello world'
Array = Elements
-> [a('hello world', {href:'facebook.com'}), img({src:'static/cat.gif'})]
more on cook.js!