create array in javascript with Html.action - javascript

I'm trying to create an array of strings in javascript by calling a function in my MVC controller and passing back an array of strings. This pretty simply just isn't working and I'm not sure what i need to do to amend this. below you can see both my javascript and controller code. Any help is greatly appreciated
javascript:
var optionString = #Html.Action("PopulateDashboardDropdown", "Embed", new { Dashboards = Model[0][0].Dashboards });
Controller:
public string[] PopulateDashboardDropdown(ODataResponseListDashboard[] dashboards)
{
string email = "";
//loop that finds the groupID assigned to the currently logged in user
foreach (Claim claim in ClaimsPrincipal.Current.Claims)
{
if (claim.Type == "emails")
{
email = claim.Value;
email = email.ToLower();
}
}
string[] orgs = GetOrgs(email);
string[] retVal = new string[orgs.Length];
bool[] admin = new bool[orgs.Length];
for (int i = 0; i < orgs.Length; i++)
{
admin[i] = isAdmin(orgs[i], email);
retVal[i] = "";
}
//loop that creates a string to emulate the innerHtml of a dropdown selector based on the names of all dashboards in the workspace
for (int i = 0; i < orgs.Length; i++)
{
for (int j = 0; j < dashboards[i].Value.Count; j++)
{
if (dashboards[i].Value.ElementAtOrDefault(j).DisplayName.Contains("Admin"))
{
if (admin[i])
{
retVal[i] += "<option>" + dashboards[i].Value.ElementAtOrDefault(j).DisplayName + "</option>";
}
}
else
{
retVal[i] += "<option>" + dashboards[i].Value.ElementAtOrDefault(j).DisplayName + "</option>";
}
}
}
return retVal;
}

Well, from isn't clear what is the error or what happens exactly but I see a couple of problems. I suggest the following in order to fix the code:
1) Change the result of your controller method to JsonResult:
public JsonResult PopulateDashboardDropdown(ODataResponseListDashboard[] dashboards)
{
...
return this.Json(retVal);
}
2) Get your data via an ajax call (note: you need to insert the proper url in http format. The Http.Action/Razor will not work in javascript):
$.getJSON(myUrl, function (data) {
var optionString = data;
...
});

Related

Tableau Javascript API

Can you explain the functions below:
viz = new tableau.Viz(containerDiv, url, options);
function listenToMarksSelection() {
viz.addEventListener(tableau.TableauEventName.MARKS_SELECTION, onMarksSelection);
}
function onMarksSelection(marksEvent) {
return marksEvent.getMarksAsync().then(reportSelectedMarks);
}
function reportSelectedMarks(marks) {
var html = "";
for (var markIndex = 0; markIndex < marks.length; markIndex++) {
var pairs = marks[markIndex].getPairs();
html += "<b>Mark " + markIndex + ":</b><ul>";
for (var pairIndex = 0; pairIndex < pairs.length; pairIndex++) {
var pair = pairs[pairIndex];
html += "<li><b>Field Name:</b> " + pair.fieldName;
html += "<br/><b>Value:</b> " + pair.formattedValue + "</li>";
}
}
}
This function just listen the selected mark
This one throw the selection in reportSelectedMarks
It take the marks and write it in an HTML file in a '<'li'>'.
The fieldname would probably be a String and in the value it depend what you are workin with.
So basically these functions would be useful to dynamically print a selected mark on a graph or something like that and print a fielname and a value for that one.

Problems with Arrays on Angular 5

I have this problem:
I have a search in the component "Table" (PrimeNg).
This search is to start when I post a character in the input. The search is correct, but when I clean the entry, the values do not return. This line at the beginning is just for this "this.groupExamples = this.Examples group;" but apparently when I change the elements of an array the other is affected.
public getGrupoExames(){
this.serviceExames.getGrupoExames()
.subscribe((response)=> {
this.grupoExames = response;
this.grupoExamesAux = response;
}, (erro)=> {
console.log("Erro");
});
}
private filtarGrupoExames(event){
let filtro: GrupoExame[] = [];
this.grupoExames = this.grupoExamesAux.slice();
for(let i = 0; i < this.grupoExames.length; i++) {
let grupo = this.grupoExames[i];
let listaExames = [];
for(let j = 0; j < grupo.exames.length; j++){
let exame = grupo.exames[j];
if(exame.nome.toLowerCase().indexOf(event.toLowerCase()) == 0) {
listaExames.push(exame);
}
}
grupo.exames = listaExames;
filtro.push(grupo);
}
this.grupoExames = filtro;
}
I suppose that you display whatever is inside your grupoExames, if that is correct you can try this structure
if(event.target.value.length > 1) {
do the filter
}
else {
this.getGrupoExames();
}
Maybe another more ambiguous solution is to create a button to delete the filter and access to all the content .
Hope it helps you!

Set Tuple of List to ViewData Mvc C#

I am adding some data in List of Tuple type like this in Razor view
List<Tuple<int, int, string>> Downloadlist = new List<Tuple<int, int, string>>();
And adding items to this list
Downloadlist.Add(new Tuple<int, int, string>(11, 7, "somedata"));
Now I would like to access the array of data in javascript
<script>
var listofdownloadpages = '#ViewData["DownloadPages"]';
if (listofdownloadpages != null) {
alert(listofdownloadpages.length);
for (var i = 0; i < listofdownloadpages.length; i++) {
alert(listofdownloadpages[i].wishid + ' ' + listofdownloadpages[i].remain);
}
}
else {
alert("not found anything");
}
But this not giving me the items in correct way please help.
This will work
Controller
public ActionResult Test()
{
List<Tuple<int, int, string>> Downloadlist = new List<Tuple<int, int, string>>();
Downloadlist.Add(new Tuple<int, int, string>(11, 7, "somedata"));
ViewData["DownloadPages"] = Downloadlist;
return View();
}
View & JS
<script>
var listofdownloadpages = #Html.Raw(Json.Encode(#ViewBag.DownloadPages));
if (listofdownloadpages != null) {
alert(listofdownloadpages.length);
for (var i = 0; i < listofdownloadpages.length; i++) {
alert(listofdownloadpages[i].Item1 + ' ' + listofdownloadpages[i].Item2);
}
}
else {
alert("not found anything");
}
</script>

Getting javascript variable in Scala

I'm trying to use a varible from javascript in a Scala array.
I need to get all the objects from this list.
entryType is a scala list.
var options = "";
for (t = 0 ; t < #entryTypes.size(); t++) {
#defining('t') { i =>
alert(#i)
options += "<option value='0'selected='selected'>#entryTypes(i).title</option>";
}
}
The thing is that I can't access t, if i try to put #defining(t' { i=> I get that this is not a scala variable.
What should I do?
Try this:
var options = "";
var entryTypes = #{Html(Json.stringify(Json.toJson(entryTypes)))};
for (t = 0 ; t < entryTypes.length; t++) {
alert(t);
options += "<option value='0'selected='selected'>" + entryTypes[t] + "</option>";
}
}

Transfering php variables to javascript variables in a php function

I'm trying to transfer php variables, that I have pulled out of a database, into three different javascript arrays. I use a php function to dynamically create a css dropdown menu, and then use a php loop to transfer the php variables into the javascript arrays. I then try to use a javascript function to initialize the attributes of the css menu. The same function is called from each of the links of the menu to update the menu based on the javascript arrays.
Here is the php function:
function createMenu()
{
//create the proper drop down menu, based on the total number of games played and the max number of games
$totalVods = count($this->VodID);
$menuArray = array();
for($i = 0; $i < $totalVods; ++$i)
{
if ($this->currentVodID != $i)
{
$menuArray[] = ($i+1);
}
}
if ( $totalVods < $this->MaxGames )
{
for ($i = $totalVods; $i < $this->MaxGames; ++$i)
{
$menuArray[] = ($this->currentVodID+1);
}
}
$totalGames = count($menuArray);
printf("<p>$this->Name</p>");
printf("<div id='cssmenu2'>");
printf('<ul>');
if ($menuArray)
{
printf('<li id="vod1" class="has-sub last"><span></span><img class="arrow" src="/images/Arrow.png">');
printf('<ul>');
if ($totalGames > 1)
{
for ($j = 0; $j < ($totalGames - 1); ++$j)
{
$vodNum = 'vod'. ($j+2);
printf("<li id='$vodNum' onclick=''><span></span></li>");
}
}
$vodNum = 'vod'. ($totalGames + 1);
printf("<li id='$vodNum' class='last' onclick=''><span></span></li>");
printf('</ul>');
}
else
{
printf('<li id="vod1"><span>Game 1</span>');
}
printf('</li>');
printf('</ul>');
printf('</div>');
//---------------------------------------------------
// function works fine up till here
// ------------------------------------------------
printf('<script>');
printf('alert("Right after totalGames");'); /* If I take this part out, up till the next comment, the rest works, but none of this part, even the alerts, works */
for($i = 0; $i < $totalVods; ++$i)
{
printf("vodName[$i] = 'Game ". ($i + 1) ."';");
printf("alert('vodName[$i]= '+vodName[$i]);");
$this->VodObject->selectVod($this->VodID[$i]);
$address = $this->VodObject->returnVod();
printf("vodAddress[$i] = '$address';");
$date = $this->VodObject->returnDate();
printf("vodDate[$i] = '$date';");
}
if ($totalVods < $this->MaxGames )
{
for ($i = $totalVods; $i < $this->MaxGames; ++$i)
{
printf("vodName[$i] = 'Game ". ($i + 1) ."';");
$gameNum = $i +1;
$address = "<div class='matchNoVOD'>There is no Game $gameNum<br />Series ended before this game.</div>";
printf("vodAddress[$i] = '$address';");
printf("vodDate[$i] = '';");
}
}/* End of the section that is having problems- if I take this out, the rest of the alerts work */
printf('alert("Right before window.onload");');
printf('window.onload = function() { switchVod(0); };');
printf('</script>');
}
In the javascript part of the above function, I access a php class called vodObject- that just accesses the database and returns the strings I want to place in the javascript array.
The javascript function that updates the css menu is placed in the part of the html, and looks like this:
<script>
var vodName = Array();
var vodAddress = Array();
var vodDate = Array();
function createfunc(i)
{
return i;
}
function switchVod(vodID)
{
alert("switchVod ran");
alert('vodID= ' + vodID);
var x=document.getElementById("vod1");
var y = x.getElementsByTagName("span");
y[0].innerHTML = vodName[vodID];
for (var i=0; i < vodName.length; i++)
{
if ( i != vodID)
{
var id = createfunc(i);
var gameNum = i + 2;
var gameID = "vod" + gameNum;
var x = document.getElementByID(gameID);
var y = x.getElementsByTagName("span");
y[0].innerHTML = vodName[i]
x.onclick = function() { switchVod(id); }
}
}
alert("after for loop");
alert("1");
document.getElementById('vodObj').innerHTML = vodAddress[vodID];
alert("2");
document.getElementById("vodDate").innerHTML = vodDate[vodID];
alert("finished");
}
</script>
The createfunc(i) is meant to get around the closure issues I heard about.
Any ideas about what I can try to fix my code? Thank you for your help, in advance!
In the JS code, you can just use var city = '<?=$city;?>';, for example.
If I got you right, you can make it using AJAX. The PHP file while print this:
echo json_encode($your_php_array);
Then, using JQuery $.getJSON method
$.getJSON('json.php', function(response) {
/* do your stuff here */
console.log(response); // This var has the json object
});
Let me know if it's useful.

Categories