Output JavaScript from Razor - javascript

I have an ASP.NET MVC app. One of the views in my app has some JavaScript. I want to set the value of a JavaScript variable based on a value in the ViewBag. If the ViewBag value exists and is not null, I want to use it. Otherwise, I want to assign an empty string value to the JavaScript variable. Here's what I'm currently trying:
<script type='text/javascript'>
function formatItem(item) {
var itemName = #(ViewBag.ItemName ? ViewBag.ItemName : '');
alert(itemName);
}
</script>
This block throws an error that says:
Compiler Error Message: CS1011: Empty character literal
Is there a way to do what I'm trying to do? If so, how?
Thanks!

You just need to use an empty string instead of a character literal (double quotes versus single quotes):
<script type='text/javascript'>
function formatItem(item) {
var itemName = '#((!string.IsNullOrEmpty(ViewBag.ItemName)) ? ViewBag.ItemName : "")';
alert(itemName);
}
</script>
Your only real problem was that you used '' instead of "". '' Means a character, "" means a string;

You need double quotes and not single quotes.
var itemName = '#(String.IsNullOrEmpty(ViewBag.ItemName) ? ViewBag.ItemName : "")';
even better you might want to use the String object:
var itemName = '#(String.IsNullOrEmpty(ViewBag.ItemName) ? ViewBag.ItemName : String.Empty)';

Related

Javascript name field masking (Using regular expression)

i need to mask a name and i want it in Script.
i have a list format data.
Following is my jsp which put data in a variable.
<c:forEach value="${test}" var="v"/>
<c:set var = "nametest" value="${v.name}"
i only need names to be shown on the screen. so i made a variable only contains names. The problem is my script function doesn't look like
contain my data correctly.
Following is my script.
function maskingName(nametest){
var a = "${nametest}"
if (a === undefined || a ===''){
return '';
}
var pattern = /.$/;
return a.replace(pattern,"*");
}
after running it, i only get the last name (there are 10 names and it shows the only the last one)without masking.
My question is
1. how can i use List format in my script function?
2. why does the regular expression not working?
Thank you!
I have written a small java code that might help you understand better
static String maskingName(String nametest) {
if (nametest == null || nametest == "") {
return "";
}
String pStr = ".$" // ".*$";
Pattern pattern = Pattern.compile(pStr);
return pattern.matcher(nametest).replaceAll("***");
}
For input '12345' or '345345', the output will be '1234***' or '34534***'
Replacing pStr=".*$" will give output ******

How to split data with square brackets while declaring parameter in json

I am passing some data from js file to handler which in turn gets result from SP. I have a parameter like ID = abc[123]. but i have to pass only 123 as value to ID to SP.
This is how im declaring parameter in js
var parameters = JSON.stringify({
"ID": JSON.stringify(EditedID).replace(/]|[[]/g, '')
});
But i am getting error like invalid ID
Kindly help
Currently, you are replacing the regex with empty space, so it will return the result 'abc123'. What you actually need is getting the string inside the brackets. You can use the below code to do it.
var EditedID = "abc[123]"
var regex = /\[([^\[\]]*)\]/
var result = ""
match = JSON.stringify(EditedID).match(regex)
if (match != null) {
result = match[1]
}
"result = match[1]" means that it will assign the value inside the brackets to result. If you want the value with both brackets, use match[0].
I assume that your EditedID is an object and somehow it will need the method "JSON.stringify" to make it become String. If your EditedID is already a String, just replace the match value to make it simpler
match = EditedID.match(regex)
If there is not match, the code won't run into the if condition so the value of result will just be an empty String.

Store a jQuery selector into a string and use it

The jQuery selector I want to store in a string variable named "jQuerySelector" in Java is :
$('h3.icon').parents('.head').find('h5:contains(Input)')
Then use it as follows:
String result = "return $(\"" + jQuerySelector + "\").get(0);";
I am facing syntax error when I initialized "jQuerySelector" as follows and run:
String jQuerySelector = "('h3.icon').parents('.head').find('h5:contains(Input)')";
My only requirement is to store the above selector query into a string and use it for running the above return statement.
Can anybody help me out please?

How to pass multiple parameter on dynamic link function jquery function C#?

I have one c# web application in which put one link dynamically like,
if (oObj.aData[1] == '2') {
Id = oObj.aData[7];
Name = oObj.aData[2];
alert(Name);
return ' Show ';
//this is
}
function like,
function Show(id,name)
{
alert('calling');
}
but my function not calling.
Is any syntax error or anything else which I forgetting?
Please help.
You need to pass Name in quotes(''), with in quotes to be treated as string parameter. Otherwise they will be treated as JS variable which obviously you have not defined, You must be getting error 'example string' is not defined. in browser console.
return ' Show ';
Note: If Id is a string, also pass it in quotes('')
This may be of some help.
Starting from Firefox 34 and Chrome 41 you will be able to use an ECMAScript 6 feature called Template Strings and use this syntax:
String text ${expression}
Example:
var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b}.`);
// "Fifteen is 15.
source: JavaScript Variable inside string without concatenation - like PHP

Viewdata in jquery syntax

I am working on an asp.net MVC application. I want to access Viewdata and assign it to Javascript variable
var LeaveDays = #(Html.Raw(ViewData["LeaveDays"]));
but it says syntax error at semi colon ; What is syntax. If i remove semi colon, it says statement not terminated. In both cases because of Js error, other scripts are not run on button click or page refresh
I want to assign the value to var
Please suggest.
Pass you value in the quotes.
Use
var LeaveDays = '#(Html.Raw(ViewData["LeaveDays"]))';
try this....
if want to assign to var :
# { var LeaveDays = ViewData["LeaveDays"]; }
or to display :
#Html.Raw(ViewData["LeaveDays"])

Categories

Resources