Passing javascript parameter from codebehind error - javascript

I use this script to call a javascript from codebehind.
ClientScript.RegisterStartupScript(this.GetType(), "Exist", "<script language='javascript'>ConfirmRedirect('" + url + "','" + msg + "');</script>", true);
and my javascript code is
function ConfirmRedirect(url,msg)
{
alert(msg);
window.location.href = url;
}
Am getting ')' expected error.
What am missing here? If am calling javascript without paramters then it is working.

Remove the Script tag and it will work, this worked for me:
ClientScript.RegisterStartupScript(this.GetType(), "Exist", "ConfirmRedirect('" + url + "','" + msg + "');", true);

View the HTML source and include it in your question/post.
You have probably just not escaped the msg enough. It can for example not contain single quotes ' or line breaks.
UPDATE
A simple solution would be to escape all single quotes using Replace().
ClientScript.RegisterStartupScript(this.GetType(), "Exist", "<script language='javascript'>ConfirmRedirect('" + url + "','" + msg.Replace("'", "\'") + "');</script>", true);

Probably the msg parameter contain symbols like the '
Then the code will be something like
<script language='javascript'>
ConfirmRedirect('/myurl/somthing.aspx','Here's my message');
</script>
And there wait for the close parenthesis.

Replace your msg varriable. Use this one---
ClientScript.RegisterStartupScript(this.GetType(), "Exist", "javascript:ConfirmRedirect('" + url + "','" + msg.Replace("'","") + "');", true);

Related

Dynamically replacing HTML with getJSON by click of button

I have a webpage that displays a news story in the main body, and has a side navigation bars where four other stories are listed. I am trying to use json files to swap out the html text in the main body. Each story has it's own json file. Here is my current javascript code:
$(document).ready(function() {
$("#nav_list a").click(function(evt) {
buildName = "../json_files/" + $(this).attr("title") + ".json";
alert(buildName);
document.getElementById("main").innerHTML = "";
$.getJSON(buildName, function(data) {
$.each(data, function() {
$.each(this, function(key, value) {
$("#main").append(
"<h1>" + value.title + "</h2>" +
"<img src='" + value.image + "'>" +
"<h2>" + value.month + "<br>" + value.speaker + "</h2>" +
"<p>" + value.text + "</p>";
);
}); // inner each
}); // outer each
)}; // end of getJSON
}); // end click
}); // end ready
Notes:
The alert(buildName) is for my own testing.
The next line (w. the innerHTML) should clear the current body content.
** NOTE: This works if I have the $.getJSON method commented out! Otherwise both this and my alert() are entirely ignored.
Because each store has it's own json file, I questioned the necessity of the muliple $.each methods within the getJSON. It didn't make a difference (the format I have below is from my textbook and has worked on a single json file with multiple entries).
I even tried not clearing the initial innerHTML and overwriting, but I may have had some syntax wrong. Here is that attempt:
$.getJSON(buildName, function(data) {
$.each(data, function(key, value) {
$("#main").append(
("#main h1").innerHTML.replace("<h1>" + value.title + "</h2>");
("#main img").innerHTML.replace("<img src='" + value.image + "'>");
("#main h2").innerHTML.replace("<h2>" + value.month + "<br>" + value.speaker + "</h2>");
("#main p").innerHTML.replace("<p>" + value.text + "</p>");
)
}); // endeach
)}; // end of getJSON
What do you guys think? I am absolutely stumped.
Remove the semi-colon at the end inside your .append(). Otherwise, I'm not sure. I wanted to comment this instead of answering but I lack the reputation. With your second attempt, those replace calls shouldn't be made inside the .append(). Good luck!
I think that the problem might be your json path that you construct.
Try using a standard path "../file.json" or "file.json" to check if you have the result you want or if the $.getJSON() is still ignored.
About the other errors: What is your devel. environment?
I also noticed that you have a bracket mismatched in your append function at the title part. So,
"<h1>" + value.title + "</h2>" +
would have to be changed to..
"<h1>" + value.title + "</h1>" +
I have re-created a sample of your site and it all seems to run fine using your code and .json files.
I just needed to modify the code as shown below. In this case, if you have a heading it will also clear the heading in your website.
<!--json retrieve script starts here -->
<script>
$(document).ready(function(){
$(":button").click(function() {
buildName = "../json_files/" + $(this).attr("title") + ".json";
alert(buildName);
//$("#main").empty();
document.getElementById("main").innerHTML = "";
$.getJSON(buildName, function(data){
//$.each(data, function() {
// $.each(data, function(key, value){
$("#main").append(
"<h1>" + data.title + "</h2>" +
"<img src='" + data.image + "'>" +
"<h2>" + data.month + "<br>" + data.speaker + "</h2>" +
"<p>" + data.text +"</p>"
);
// });
//});
});
});
});
</script>
<!--json script end here -->
NOTE: I have swapped the link with button to wire the event for this example.
You can also use multiple file entries in a single .json file in the format shown below:
{
"story1":"/jsonfile1.json",
"story2":"/jsonfile2.json",
"story3":"/jsonfile3.json"
}
which you would then parse with an $.each(data,function(key,value) where value would be the filename to be requested via $.getJSON so you can have multiple entries handled by a single file.
There were a few syntax errors - a parenthesis and curley bracket out of order, misplaced semi-colon, things of the like. The logic was correct.
Thanks all for the replies!

bootbox.alert not working from code behind

I am importing data to DB from excel using bootstrap file uploader. After data import I need to show a message to user. So I have below code
string strScript = "bootbox.alert('" + Resources.Resource.Success_SaveUserInfo + "');";
Page.ClientScript.RegisterStartupScript(this.GetType(), "UserSave", strScript, true);
But it is not working. Page get freeze instead of alert. But if I use below code it work.
string strScript = "alert('" + Resources.Resource.Success_SaveUserInfo + "');";
Page.ClientScript.RegisterStartupScript(this.GetType(), "UserSave", strScript, true);
I have already added bootbox.min.js. So it is not issue.
You can do like this
string strScript = "<script type = 'text/javascript'>bootbox.alert('" + Resources.Resource.Success_SaveUserInfo + "');</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "UserSave", strScript, true);
OR
Call javascript function it's highly recommended and reusable as well
Page.ClientScript.RegisterStartupScript(this.GetType(), "UserSave", CustomalertFunction('" + Resources.Resource.Success_SaveUserInfo + "'), true);
and write a javascript function
function CustomalertFunction(message)
{
bootbox.alert(message);
}

JS hide email function not working

I took the code below from a wider document, and tried to include it between 2 script tags, but for some reason it's not working (nothing happens).
Do I need to add some document ready syntax or something like this?
Thanks,
<script>
function sendAnnotatedMailTo(name, company, domain, subject, body) {
locationstring = 'mai' + 'lto:' + name + '#' + company + '.' + domain + "?subject=" + escape(subject) + "&body=" + escape(body);
window.location.replace(locationstring);
}
</script>
You only defined a function but didn't call it.
You have to call your function like this:
Send mail
This will open your mail client and prepare an email to name#democompany.domain.tld with the subject "Subject of mail" and the bodytext "Body of mail".
Btw: You shouldn't use the deprecated JS function "escape" anymore. Use encodeURI instead:
<script>
function sendAnnotatedMailTo(name, company, domain, subject, body) {
locationstring = 'mai' + 'lto:' + name + '#' + company + '.' + domain + "?subject=" + encodeURI(subject) + "&body=" + encodeURI(body);
window.location.replace(locationstring);
}
</script>

How to pass a variable in ajax append function (into html element with razor)?

I need to pass the Id of a object into a html element (razor part), but it doesn't recognize it. Look like the Id is not in its scope, or something. Is there a way to pass the value into the razor part of my html element in the append function?
$.ajax({
data: data,
url: url + "?searchTerm=" + data
}).success(function (response) {
console.log(response);
var table = $('#companyTable');
var tBody = table.children('tbody');
tBody.html("");
var textbox = document.getElementById("searchBar");
textbox.value = "";
tBody.append(
"<tr><td>" +response.CompanyName + " </td><td>" +
response.CompanyIdNumber + "</td><td>" +
response.CompanyTaxNumber + "</td><td>" +
"<p><button onclick=\"location.href='#Url.Action("Edit", "Company", new { #id = response.CompanyId })'\"> Edit</button></p>" +
"</td></tr>"
);
table.removeClass("hidden");
var originalTable = $('#originalTable');
originalTable.remove();
}).error(function (response) {
console.log(response);
});
}
Thank you.
I do those things this way:
+ "<p><button onclick=\"location.href='#(Url.Action("Edit", "Company"))?id=" + response.CompanyId + "'\">Edit</button>"
You are totally missing the concept of server-side rendering and browser execution. Consider this example, your server renders your js code, and just leaves all work to browser, then browser stars to execute Ajax request somehow(button click), when Ajax completed - you have a response value, but this value exists only inside browser context, so it doesn't make sense to pass value into razor, as it already done its work while rendering your file
Now, what to do? The simplest solution would be to hardcore Url of company edit by yourself, as razor simply doesn't know anything what's happening client-side, example:
location.href="/company/1/edit" //where 1 is id from Ajax request
The easiest complete solution is
public ActionResult WhateverMethod()
{
// ....
var urlHelper = new UrlHelper(this.ControllerContext.RequestContext);
response.Url = Url.Action("Edit", "Company", new { #id = response.CompanyId });
// ....
}
And
tBody.append(
"<tr><td>" +response.CompanyName + " </td><td>"
+ response.CompanyIdNumber + "</td><td>"
+ response.CompanyTaxNumber + "</td><td>"
+ "<p><button onclick=\"location.href='" + response.Url + "'\"> Edit</button></p>"
+ "</td></tr>");
Calling a Razor methods in JavaScript is going to cause you nothing but grief.
response.CompanyId is considered as string , so try by concatenating it as below
var a="location.href='#Url.Action("Edit", "Company", new{#id='"+response.CompanyId+"'})'"
response.CompanyId ( "<tr><td>" +response.CompanyName + " </td><td>" +
response.CompanyIdNumber + "</td><td>" +
response.CompanyTaxNumber + "</td><td>" +
"<p><button onclick=\""+a +"\"> Edit</button></p>" + "</td></tr>")

tinyMce shortcuts

I am working with an asp.net website where we have implemented shortcuts in our page master, but these don't seem to work when the tinymce editor has focus. is there any way to solve this issue? it doesn't matter if it's at master page level or tinymce-level.
I have tried to create custom methods via the addShortcut method but this causes my javascript to error.
page.ClientScript.RegisterStartupScript(page.GetType(), new Guid().ToString(), "ShortCutModule();", true);
string enableShortcuts = #"function enableShortcuts(){"+
#"tinyMCE.get('"+"myKey2"+this.ID+#"').addShortcut(""Ctrl+Shift+f12"",""nix"",""jourcut"");";
page.ClientScript.RegisterStartupScript(page.GetType(), new Guid().ToString(), enableShortcuts, true);
page.ClientScript.RegisterStartupScript(
page.GetType(),
"MyKey2" + this.ID, #"<script type=""text/javascript"" >" +
#"tinyMCE.init({" +
#"oninit : ""enableShortcuts"","+
#"mode: ""exact""," +
#"elements: """ + this.ID + #"""," +
#"theme: ""advanced""," +
#"plugins: ""spellchecker,advhr,insertdatetime,preview""," +
#"theme_advanced_buttons1: ""bold,italic,underline,|,outdent,indent,|,cut,copy,paste,|,undo,redo""," +
#"theme_advanced_toolbar_location: ""top""," +
#"theme_advanced_toolbar_align: ""left""," +
#"theme_advanced_statusbar_location: ""bottom""," +
"custom_shortcuts : false," +
"theme_advanced_path : false," +
"setup : function(ed) {" +
"ed.addCommand('jourcut', function() {CutFromJournal();});" +
"}" +
"});" +
"</script>",
false);

Categories