So I have been looking through relevant questions and I can't figure out exactly why my script tag is malformed.
<script language="javascript" type="text/javascript">
var showME = false;
var showSuffix = "";
#if (ViewData["showME"] != null && ViewData["showSuffix"] != null)
{
<text>
showME = #(Convert.ToBoolean(ViewData["showME"]) ? "true" : "false");
showSuffix = '#Html.Raw(Json.Encode(ViewData["showSuffix "]))';
</text>
}
</script>
EDIT!
The answer below is correct but I tracked down the malformed part to this line.
var videoHelpUrl = #(Url.Action("Index", "Help", new { Id = 46 }));
Try this:
<script language="javascript" type="text/javascript">
var videoHelpUrl = '#Url.Action("Index", "Help", new { Id = 46 })';
console.log(videoHelpUrl);
</script>
console.log will output the Url.
Note: Always keep in mind that everything following # in a Razor view will be processed by the Razor engine. This is why you can surround #Url.Action(...) with quotes. It will be processed first by Razor engine and then by Javascript when it is executed.
If you try using double {{ }} as in;
#{
if (ViewData["showME"] != null && ViewData["showSuffix"] != null)
{
<text>
showME = #(Convert.ToBoolean(ViewData["showME"]) ? "true" : "false");
showSuffix = '#Html.Raw(Json.Encode(ViewData["showSuffix "]))';
</text>
}
}
See if that works.
Related
In a c# MVC project, I was given a view by a front-end designer that contains this little script:
<script>
$('#PhaseDD').change(function () {
var chosenValue = $(this).val();
$('.ProcessDD').hide();
if (chosenValue == "")
$('#DefaultProcess').show();
if (chosenValue == "Planning")
$('#PlanningProcess').show();
if (chosenValue == "Procurement")
$('#ProcurementProcess').show();
if (chosenValue == "Installation")
$('#InstallationProcess').show();
if (chosenValue == "Closure")
$('#ClosureProcess').show();
});
</script>
I would like to replace all the hard-coded options with a list that comes from the model. Something like this...
<script>
$('#PhaseDD').change(function () {
var chosenValue = $(this).val();
$('.ProcessDD').hide();
if (chosenValue == "")
$('#DefaultProcess').show();
// loop over a list from the model here
if (chosenValue == " loop-item-name ")
$('# loop-item-name + Process').show();
// end loop
});
</script>
Is this possible? If so, how? And am I even going about this the right way? I was thinking I could use razor syntax, but that isn't working.
You can not compare a C# variable to a JS variable. But you can use razor to create a JS variable from a C# variable.
Here is how to fill a JS array with the values of a C# array:
#{
// fetch this from ViewModel if it needs to be dynamic
var cSharpNames = new [] { "Planning", "Procurement"};
}
<script>
var jsNames = []; // this is a JS array
#foreach(var name in cSharpNames) {
<text>jsNames.push(#name);</text>
}
</script>
Then use the indexOf() method to search in the jsNames array as has been shown by Jeremy.
I'd just make an array, check to see if the value exists within it, and if it does show it. Something like this:
<script>
$('#PhaseDD').change(function () {
var chosenValue = $(this).val();
var processes = ['Planning', 'Procurement'];
$('.ProcessDD').hide();
if (chosenValue == "")
$('#DefaultProcess').show();
if (processes.indexOf(chosenValue) > -1)
$('#' + chosenValue + 'Process').show();
});
</script>
I was overthinking this.
$('#PhaseDD').change(function () {
var chosenValue = $(this).val();
$('.ProcessDD').hide();
if (chosenValue == "")
{
$('#DefaultProcess').show();
}
else
{
$('#' + chosenValue + 'Process').show();
}
});
function setRedirect()
{
var redirectDest = "This is additional description <a href="http://opensourceforgeeks.blogspot.in/">Click Me</a>.";
if(redirectDest != null && redirectDest != '')
{
document.getElementById("RedirectDestElem").innerHTML = redirectDest;
}
}
redirectDest is populated from Spring controller. So the function is actually
function setRedirect()
{
var redirectDest = "${redirectDest}";
if(redirectDest != null && redirectDest != '')
{
document.getElementById("RedirectDestElem").innerHTML = redirectDest;
}
}
This appends current url base address to http://opensourceforgeeks.blogspot.in and then redirects. I dont want this to happen. I have to convert " to " in Java code (escape it) so that my java script does not break. Otherwise it will be
var redirectDest = "This is additional description Click Me.";
which will break.
Why don't you enclose redirectDest in single quotes?
var redirectDest = '${redirectDest}';
you can use the escape sequence "\"
so your text will be like below:
var redirectDest = "This is additional description Click Me.";
I have the following poorly-formed JS:
<script type="text/javascript", id="changeTabScript">
function changeTab(type) {
String.prototype.contains = function(str) {return this.indexOf(str) != -1;};
var lbl = document.getElementById('searchLabel').Value;
if (lbl.contains("Officer"))
{
type = "Officer";
}
if (type == "Officer")
$('#tab-container').easytabs('select', '#tabs1-officer');
else
$('#tab-container').easytabs('select', '#tabs1-company');
};
</script>
I have implemented Page.RegisterStartupScript("changeTab", "<script language=JavaScript>changeTab </script");,
however I haven't a clue how ClientScript.RegisterStartupScript is formed. The "key" is something I am unfamiliar with, how do I use the newer implementation?
Hi I have a page where after confirmation email is displaying. I want to display that email inside image link.
For this I have used this code, but I get email variable null here.
<HTML>
<head>
<script type="text/javascript">
var formData = function() { var query_string = (location.search) ? ((location.search.indexOf('#') != -1) ? location.search.substring(1, location.search.indexOf('#')) : location.search.substring(1)) : '';
var elements = [];
if(query_string) {
var pairs = query_string.split("&");
for(i in pairs) {
if (typeof pairs[i] == 'string') {
var tmp = pairs[i].split("=");
var queryKey = unescape(tmp[0]);
queryKey = (queryKey.charAt(0) == 'c') ? queryKey.replace(/\s/g, "_") : queryKey;
elements[queryKey] = unescape(tmp[1]);
}
}
}
return {
display: function(key) {
if(elements[key]) {
document.write(elements[key]);
}
else {
document.write("<!--If desired, replace everything between these quotes with a default in case there is no data in the query string.-->");
}
}
}
}
(); </script>
</head>
<body>
<!-- Offer Conversion: Safe Binary Trades -->
<script type="text/javascript">formData.display("email")</script>
<img src="http://mountainfallsmedia.go2cloud.org/SL22?adv_sub="email" width="1" height="1" />
<!-- // End Offer Conversion -->
</body></HTML>
If you look at the last lines of code you can see formData.display("email"), it uses to display email, it is working fine, but its not working in case of
<img src="http://mountainfallsmedia.go2cloud.org/SL22?adv_sub="email" width="1" height="1" />
I have tried by passing formData.display("email") instead of email, but it still returns blank.
I'm not sure what exactly what your question is, or exactly what you're trying to do, but you may want replace
src="http://mountainfallsmedia.go2cloud.org/SL22?adv_sub="email"
with
src='http://mountainfallsmedia.go2cloud.org/SL22?adv_sub="email"'
(Note the single quotes encapsulating your url.)
I know there are a lot of post about this, but i've been looking to do this all day.
What i try to acheive here is to click on a row in a GridView, then bring the page to scroll to that position, like an anchor in html would do.
This, is my link that i'll use to scroll. I call a function in my js file. This is in my GridView.
<asp:LinkButton runat="server" OnClientClick="window.scrollTo(0, GetPosition(this))" CommandName="select" ID="InkSelect" Text="SELECT" />
Then, i call this function in my js file, linked like this, just in case:
<script type="text/javascript" src="~js/monjs.js"></script>
In monjs.js, here is the function:
function GetPosition(element) {
var top = 0;
var e = document.getElementById(element);
while (e.offsetParent != undefined && e.offsetParent != null) {
top += e.offsetTop + (e.clientTop != null ? e.clientTop : 0);
e = e.offsetParent;
}
return top;}
And Visual studio is highlighting this line:
...... <a onclick="window.scrollTo(0, GetPosition(this));" .....
I tried many other way to do this, registering a script in the vb file, hardcoding window.scrollTo(0,100) in the onclick attribute, i'm out of ideas.
I tried row.focus, don't mention this one.
Thanks.
<a onclick="window.scrollTo(0, GetPosition(this));"
^
|
An Object
function GetPosition(element) {
var top = 0;
var e = document.getElementById(element);
^
|
Expecting a string
You are passing in an object and acting like it is a string.
var e = document.getElementById(element);
needs to be
var e = element;
If your function needs to handle both an object or a string, you can either pass in this.id with the onclick handler
OnClientClick="window.scrollTo(0, GetPosition(this.id))"
or do a typeof check.
var e = typpeof element === "string" ? document.getElementById(element) : element;
ok I managed to do something. AFter many many tries...
i used this in my aspx file:
<asp:LinkButton runat="server" OnClientClick="return Move(this);" CommandName="select" ID="_row" Text="SELECT" />
In my aspx.vb file, i used this in my page load function:
Dim myScriptName As String = "MovePageScript"
If (Not ClientScript.IsClientScriptBlockRegistered(Page.GetType(), myScriptName)) Then
Dim myScript As New StringBuilder()
myScript.Append("<script type=""text/javascript""> function Move(element) {")
myScript.Append("var top = 0;")
myScript.Append("var e = typeof element === 'string' ? document.getElementById(element) : element;")
myScript.Append("while (e.offsetParent != undefined && e.offsetParent != null) {")
myScript.Append("top += e.offsetTop + (e.clientTop != null ? e.clientTop : 0);")
myScript.Append("e = e.offsetParent; }")
myScript.Append("window.scrollTo(0, top);")
myScript.Append("return false;")
myScript.Append("} </script>")
ClientScript.RegisterClientScriptBlock(Page.GetType(), myScriptName, myScript.ToString(), False)
End If
And used this in my web.config file:
<pages maintainScrollPositionOnPostBack="true">
It cancels the selection of the row but at least it works... I'll have to check now if I can get this to work with Telerik's Ragrid XD