How to correctly combine javascript with razor syntax - javascript

I have the following code in my razor view, I need to set some javascript variables to set the value coming from razor.
However the values of the variables are not being set.
var listPuntos =[];
function onSelect(e) {
var dataItem = this.dataSource.view()[e.item.index()];
#{
var proveedorID = 0;
<text>proveedorID = dataItem.ProveedorID</text>
var list = new UnitOfWork().PuntosVentaProveedorRepository.Get().Where(x => x.ProveedorID == proveedorID);
proveedorID = 0;
<text>listPuntos = list; </text>;
<text>
var displayText;
$.each(listPuntos, function (key, value) {
if (displayText == undefined)
displayText = value.Nombre + ', ';
else
displayText = displayText + value.Nombre + ', ';
});
document.getElementById("puntos").value = displayText.slice(0,-2);
</text>
}
}

Given your concrete example, I would start by reducing the number of <text> blocks needed by instead just wrapping the shorter C# bits with #{ … }. This improves readability & lessens confusion. For example:
var listPuntos =[];
function onSelect(e) {
var dataItem = this.dataSource.view()[e.item.index()];
#{ var proveedorID = 0; }
proveedorID = dataItem.ProveedorID;
#{ var list = new UnitOfWork().PuntosVentaProveedorRepository.Get().Where(x => x.ProveedorID == proveedorID); }
proveedorID = 0;
listPuntos = #Json.Encode(list);
var displayText;
$.each(listPuntos, function (key, value) {
if (displayText == undefined)
displayText = value.Nombre + ', ';
else
displayText = displayText + value.Nombre + ', ';
});
document.getElementById("puntos").value = displayText.slice(0,-2);
}
Next, to inject a C# value into JavaScript code being emitted by the server, you need to encode the value in JavaScript. The best way to do this is to convert it into JSON. This is done above using Json.Encode. In particular, the line reading:
listPuntos = #Json.Encode(list);
I've used Json.Encode but of course you are free to use whatever JSON library du jour that fits your project.

you should separate html code and javascript code.
First at all, don't call any server code from View when View is loading. Push all necessary arrays etc via model property in appropriate format (i.e. in json format) and then fill any client list from value of that property.
Secondly - move code like it :
var displayText;
$.each(listPuntos, function (key, value) {
if (displayText == undefined)
displayText = value.Nombre + ', ';
else
displayText = displayText + value.Nombre + ', ';
});
document.getElementById("puntos").value = displayText.slice(0,-2);
to appropriate section, like it:
#section scripts
{
<script>
.....
</script>
}

Related

Retrieving LookupValues, Javascript SharePoint 2013, Not Working

I've seen a lot of info on the above question but none of it has answered what I'm looking for, so far. I'm trying to retrieve list items that have a great number of lookup fields. I've had success getting to some of the lookup values but not others and I can't figure out why. Also, it would appear that 'null' items are not accepted in the returned data? If the lookup field does not contain a value, it throws an error? Is this correct? Below is my code. The other issue (the big issue mentioned in my title) is that lookup values where I'm trying to pull in something, other than ID or Title, throws an error: reference not found or initialized. In this instance my lookup field is referencing a calc column returned as a single line of text. So my lookup field is Course1Date/DateRange, where DateRange represents the fieldname of the calc column. Error: "The property or field has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested."
function getLookupValues(){
var clientContext = SP.ClientContext.get_current();
var list = clientContext.get_web().get_lists().getByTitle('Lookup');
var caml = new SP.CamlQuery();
caml.set_viewXml('<View><Query><Where><Geq>' +
'<FieldRef Name=\'ID\'/><Value Type=\'Number\'>82</Value>' +
'</Geq></Where></Query><RowLimit>10</RowLimit></View>');
var returnedItems = list.getItems(caml);
clientContext.load(returnedItems);
clientContext.executeQueryAsync(success, failure);
}
function success(){
var listiteminfo='';
var enumerator = returnedItems.getEnumerator();
while(enumerator.moveNext())
{
var listItem = enumerator.get_current();
if(listItem.get_item('Course1')) {
var course1 = listItem.get_item('Course1').get_lookupValue();
}
if(listItem.get_item('Course2')) {
var course2 = listItem.get_item('Course2').get_lookupValue();
}
if(listItem.get_item('Course1Date')) {
var course1Date = listItem.get_item('Course1Date').get_lookupValue();
} //throws error for this lookup field
listiteminfo += '\nCourse1: '+course1+'\nCourse2: '+course2+'\nCourse1Date: '+course1Date;
}
alert(listiteminfo);
}
function failure(){
alert("Failed");
}
You have initialize the fields to get Lookup Values. Have to load the ListItem in context. And if there is a null value in lookup field, get.lookupValue() will throw an exception. So check the field value is not null before getting lookup value. Please try my workaround below and let me know if it works.
function getLookupValues() {
var clientContext = SP.ClientContext.get_current();
var list = clientContext.get_web().get_lists().getByTitle('Lookup');
targetListItem = list.getItemById(82);
clientContext.load(targetListItem, 'Title');
clientContext.load(targetListItem, 'Course1');
clientContext.load(targetListItem, 'Course1Date');
clientContext.load(targetListItem, 'Course2');
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded() {
var resultData = "";
resultData += targetListItem.get_item('Title');
if (targetListItem.get_item('Course1') != null)
resultData += targetListItem.get_item('Course1').get_lookupValue();
if (targetListItem.get_item('Course1Date') != null)
resultData += targetListItem.get_item('Course1Date').get_lookupValue();
if (targetListItem.get_item('Course2') != null)
resultData += targetListItem.get_item('Course2').get_lookupValue();
alert(resultData);
}
function onQueryFailed(sender, args) {
alert('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}

plv8 disable execute and prepare function in eval()

How could I deactivate the access to plv8 functions in my eval?
create or replace function
js(src text, input json) returns json as $$
plv8.elog(NOTICE, 'test');
//--plv8 = null; // this would disable permanently plv8, also after another call of the function
var evalRes = eval('var output=null; ' + src + '; output;');
return JSON.stringify(evalRes);
$$ LANGUAGE plv8;
I finally found the solution:
create or replace function
public.js(src text, input json) returns json as $$
//-- select js('var a = input.test; var output = []; for(k in a) { output.push(10+a[k]); };', '{"test": [1,2,3]}'::json)
//-- select public.js('plv8.elog(NOTICE, "yoyo");', null) // should not be possible
plv8.elog(NOTICE, 'test');
var evalRes = null;
(function() {
var plv8 = null; //-- In order to disable execute, prepare...
evalRes = eval('var output=null; ' + src + '; output;');
})();
plv8.elog(NOTICE, 'test2');
return JSON.stringify(evalRes);
$$ LANGUAGE plv8;

How to parse data via url and retrive with javascript

I went through sb code and wants to implement similar code. he used:
htmlItems += '<li><a href="show-feed.html?url=' + items[i].url + '">' +
items[i].name + '</a></li>';
and used this javascript code to retrive the url and parse to a method
.on('pageinit', '#show-feed-page', function () {
var url = this.getAttribute('data-url').replace(/(.*?)url=/g, '');
Application.initShowFeedPage(url);
it works well and i want to parse three values to the method eg
<a href="showProduct.html?code='+ items[i].code +',name='+items[i].name+',price='+items[i].price+'">"and need code to retrive and parse to a method
initShowProductPage(code,name,price);
First of all, your html is wrong, you have to prepare proper query string format, the updated html mark up is:
<a href="showProduct.html?code='+ items[i].code +
'&name='+items[i].name+'&price='+items[i].price+'">"
You have to access window.location.href and parse it for the query string parameters.You can write a method which parses the url, like below:
function parseURL() {
var vars = [];
var hashes = window.location.href.slice( window.location.href.indexOf('?')+1 ).split("&");
for (var i=0;i<hashes.length;i++) {
hash = hashes[i].split("=");
vars.push( hash[0] );
vars[ hash[0] ] = hash[1];
}
return vars;
}
Then you can access them using code, name and price parameters like below:
.on('pageinit', '#show-feed-page', function () {
var hashObj = parseURL();
// To get code
var code = hashObj["code"];
// To get name
var name = hashObj["name"];
// To get price
var price = hashObj["price"];
// Now call the method
initShowProductPage(code,name,price);
});

How to convert scala list to javascript array?

Is there a simpler way of doing this?
$(document).ready(function () {
var jsArray = []
#if(scalaList != null) {
#for(id <- scalaList) {
jsArray.push('#id');
}
}
...
}
It's as simple as the following:
import play.api.libs.json.Json
val jsArr: JsValue = Json.toJson(scalaList)
You can also do that within a template:
#(list: List[Any])
#import play.api.libs.json.Json
<script type="text/javascript">
$(document).ready(function () {
var jsArr = #Json.toJson(list);
console.log(jsArr);
});
</script>
You can use mkString for this.
$(document).ready(function () {
var jsArray = #if(scalaList != null) {
[ #scalaList.mkString(",") ]}
else {[]};
}
You should omit this if statement in view. Instead of this, check null in controller and put empty list to view, so this code can be more simpler in view
$(document).ready(function () {
var jsArray = [ #scalaList.mkString(",") ];
}
You don't need this quotes ' ' around id. In javascript 1 == '1' is true
Have you tried something like:
var jsArray = new Array(#scalaList.map(x => "\"" + x + "\"").mkString(","));
or you can use a literal like
var jaArray = [ var jsArray = [#scalaList.map(x => "\"" + x + "\"").mkString(",")];
Also the if check is not required. For comprehensions are smart like that
$(document).ready(function () {
var jsArray = [#scalaList.map(x => "\"" + x + "\"").mkString(",")];
...
}
I think every answer are good but still not safe because every answers don't care about value which including ' or ". Fortunately play framework support json, so you should use json to convert to javascript array.
#(json: String)
<html>
<head>
</head>
<body>
<script>
var json = #Html(json);
var list = json.list;
</script>
</body>
</html>
package controllers
import play.api._
import play.api.libs.json._
import play.api.mvc._
object Application extends Controller {
def index = Action {
val list = List( "hoge\"hoge", "moge'mo\"ge" )
val json = Json.stringify( Json.obj(
"list" -> JsArray( list.map( JsString(_) ) )
))
Ok(views.html.index(json))
}
}

Getting null value to controller's action passing from javascript using jquery

What I tried in my project is like passing checkbox's selected value as a comma separated string to json of my controller.. but i'm not getting a value to the json action.. it shows null over there.
How can I do this? Please help me
function getIds(checkList)
{
var idList = new Array();
var loopCounter = 0;
jQuery("input[name=" + checkList + "]:checked").each
(
function()
{
idList[loopCounter] = jQuery(this).val();
loopCounter += 1;
}
);
alert(idList);
jQuery.getJSON("/Photos/CheckForIdsJson", { idList: idList });
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult CheckForIdsJson(Int32[] idList)
{
JsonResult result = new JsonResult();
result.Data = idList;
return result;
}
You can have a look at this post : AJAX Post of JavaScript String Array to JsonResult as List<string> Always Returns Null? or this one : Send list/array as parameter with jQuery getJson . It seems that you have to indicate traditional: true in your ajax call.
Use this in your script :
var did ='',
$("#tbl").find("input:checkbox").each(function (i) {
if (this.checked == true) {
did += $(this).val() + ",";
}
});
alert(did);
if (did == "") {
alert("Please Select");
return;
}

Categories

Resources