MVC pass list to jQuery and extract elements - javascript

I need to pass a list from my MVC-controller to a javascript in my view.
Here's the method in my controller
private void PopulateChart() {
var diagramItem = new DiagramPoll();
var diagramList = new List<DiagramPoll>();
diagramItem.Color = "#F7464A";
diagramItem.Label = "System 1";
diagramItem.Value = "10";
diagramList.Add(diagramItem);
diagramItem.Color = "##FDB45C";
diagramItem.Label = "System 2";
diagramItem.Value = "20";
diagramList.Add(diagramItem);
ViewBag.MyValues = JsonConvert.SerializeObject(diagramList, Formatting.None);
}
And in the script-section in the view-file:
<script>
$(document).ready(function() {
var chartValues = #Html.Raw(ViewBag.MyValues);
//This is what I would like to do:
foreach (var item in chartValues) {
var color = item.Color;
var label = item.Label;
var value = item.Value
}
});
</script>
I need to extract the variables above to send them as input parameters to a jQuery-chart.
Thank you!

For passing values from view to script you need to add it in quotes. Change your script to as below
<script>
$(document).ready(function() {
var chartValues = '#ViewBag.MyValues';
});
</script>
Also you would not be able to iterate through it, firstly you will need to convert serialized json object to proper json object.
Something like this and then run foreach over json object.
var chartData = $.parseJson(chartValues);
foreach (var item in chartData ) {
var color = item.Color;
var label = item.Label;
var value = item.Value
}
Or
var chartData = JSON.parse(chartValues);
but you will have to convert chartValues for sure

you can try something like this:
#model IList<WebApplication2.Models.DiagramPoll>
<script type="text/javascript">
$(document).ready(function() {
//This is what I would like to do:
#foreach (var item in Model) {
var color = item.Color;
var label = item.Label;
var value = item.Value;
}
});
public ActionResult About()
{
var diagramItem = new DiagramPoll();
var diagramList = new List<DiagramPoll>();
diagramItem.Color = "#F7464A";
diagramItem.Label = "System 1";
diagramItem.Value = "10";
diagramList.Add(diagramItem);
diagramItem.Color = "##FDB45C";
diagramItem.Label = "System 2";
diagramItem.Value = "20";
diagramList.Add(diagramItem);
return View(diagramList);
}

Related

Get value from the people picker and add it to a list in a person column

I have a simple JS form on my SP16 site where I added this standard people picker:
$(document).ready(function() {
initializePeoplePicker('pickerUAT');
function initializePeoplePicker(peoplePickerElementId) {
var schema = {};
schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
schema['SearchPrincipalSource'] = 15;
schema['ResolvePrincipalSource'] = 15;
schema['AllowMultipleValues'] = false;
schema['MaximumEntitySuggestions'] = 50;
schema['Width'] = '269px';
this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);
}
});
I am able to get the selected value (as a display name, email, whatever) from the picker like this:
function getEmailFromPeoplePicker(title) {
var ppDiv = $("div[title='" + title + "']")[0];
var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict.pickerUAT_TopSpan;
var userList = peoplePicker.GetAllUserInfo();
var userInfo = userList[0];
var addThisUser;
if(userInfo != null)
{
addThisUser = userInfo.Key;
}
return addThisUser;
}
And I have a list to which I can add other values taken from other form fields, usually through document.getElementById("XXX").value and this piece of code:
function addSubUser(addThisValue) {
var clientContext = new SP.ClientContext(siteurl);
var itemCreateInfo = new SP.ListItemCreationInformation();
var valueToAdd = addThisValue;
var list = clientContext.get_web()
.get_lists()
.getByTitle("UAT");
this.oListItem = list.addItem(itemCreateInfo);
oListItem.set_item('userUAT', valueToAdd);
oListItem.update();
clientContext.load(oListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
However, this code doesn't work for the value taken from the people picker. Console.log(typeof addThisUser) tells me the value I get from the picker is just a string, do I assume correctly that I cannot simply add a string to a person/group column? In any event, how can I make it work?
I think You may try to update the filed using two different methods
as lookup giving ID of user
var LookupSingle = new SP.FieldLookupValue();
LookupSingle.set_lookupId(2); // UserId
oListItem.set_item('SomeLookupColumn', LookupSingle);
as Single User Field
var singleUser = SP.FieldUserValue.fromUser('name surname');
oListItem.set_item('SomeSingleUserColumn', singleUser);
Sample test script in my local SharePoint 2016(multiple user field).
CustomPeoplePicker:
<div id="peoplePickerDiv"></div>
<input id="Button1" onclick="SaveItem()" type="button" value="button" />
<script src="/_layouts/15/sp.runtime.js"></script>
<script src="/_layouts/15/sp.js"></script>
<script src="/_layouts/15/1033/strings.js"></script>
<script src="/_layouts/15/clienttemplates.js"></script>
<script src="/_layouts/15/clientforms.js"></script>
<script src="/_layouts/15/clientpeoplepicker.js"></script>
<script src="/_layouts/15/autofill.js"></script>
<script src="_layouts/15/sp.core.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript">
$(document).ready(function () {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', sharePointReady);
})
function sharePointReady() {
context = new SP.ClientContext.get_current();
web = context.get_web();
var schema = {};
schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
schema['SearchPrincipalSource'] = 15;
schema['ResolvePrincipalSource'] = 15;
schema['AllowMultipleValues'] = true;
schema['MaximumEntitySuggestions'] = 50;
schema['Width'] = '280px';
this.SPClientPeoplePicker_InitStandaloneControlWrapper('peoplePickerDiv', null, schema);
}
function SaveItem() {
var ctx = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle("MyList");
var listCreationInformation = new SP.ListItemCreationInformation();
var listItem = list.addItem(listCreationInformation);
var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDiv_TopSpan;
// Get information about all users.
var users = peoplePicker.GetAllUserInfo();
// Get user keys.
var keys = peoplePicker.GetAllUserKeys();
var finalusers = new Array();
for (var i = 0; i < users.length; i++) {
var arryuser = users[i];
finalusers.push(SP.FieldUserValue.fromUser(arryuser.Key));
}
listItem.set_item("Title", "Title");
listItem.set_item("Requestor", finalusers);
listItem.update();
ctx.load(listItem);
ctx.executeQueryAsync(
Function.createDelegate(this, function () {
console.log(listItem);
}),
Function.createDelegate(this, function (sender, args) {
alert('Query failed. Error: ' + args.get_message());
})
);
}
</script>

How can I display my var array name in HTML textblock?

I want to display my var array names in a textblock. These need to change depending on what box is ticked in my form.
Now I can show the values in the array, but I need to display the actual name too. I am VERY new to coding, and I have trouble finding the right words to describe my problem, thus not finding any solution. I hope you can help me out.
var color_prices = new Array();
color_prices["Orange"]=1;
color_prices["Blue"]=2;
color_prices["Green"]=3;
function getColorPrice()
{
var ColorPrice=0;
var theForm = document.forms["order-form"];
var selectedColor = theForm.elements["COLOR"];
for(var i = 0; i < selectedColor.length; i++)
{
if(selectedColor[i].checked)
{
ColorPrice = color_prices[selectedColor[i].value];
break;
}
}
return ColorPrice;
}
var colorPrice = getColorPrice();
document.getElementById('colorPrice').innerHTML = colorPrice.toFixed(2);
Right now I 'stole' some code online to display the value of "orange" in my html (so "1") and this works but I have no idea how to display the value "orange" in my html.
I hope I explained it correctly.
A solution could be to change your ColorPrice variable to be an object to be able to store the color price and the color name, in my example I'm also changing the name of the variable to colorDetails to be more descriptive about what is containing
var color_prices = new Array();
color_prices["Orange"]=1;
color_prices["Blue"]=2;
color_prices["Green"]=3;
function getColorDetails()
{
//here we rename the variable and convert from integer to object
var colorDetails = {
price: 0,
name: undefined
};
var theForm = document.forms["order-form"];
var selectedColor = theForm.elements["COLOR"];
for(var i = 0; i < selectedColor.length; i++)
{
if(selectedColor[i].checked)
{
//here we store the color price inside colorDetails
colorDetails.price = color_prices[selectedColor[i].value];
//and we add this new line where we save the name of the color
colorDetails.name = selectedColor[i].value;
break;
}
}
return colorDetails;
}
var colorDetails = getColorDetails();
document.getElementById('colorPrice').innerHTML = colorDetails.name + ": " + colorDetails.price.toFixed(2);

Accessing property's array with a specific id

What i wanted to do is access random property for example let1, let2 with their first string in array which is ID "1" , "2" , "3" , "4" , "5".
brojleta is actually that ID i mentioned before, it is different from id down there(var id = item[0][1]). What i need is to get all other strings based on their ID. I tried it like this :
var data = {
let1:[["1","2","10.2.2019.","11.2.2019.","Beograd Aerodrom","Amsterdam Aerodrom","30","12000"]],
let2:[["2","4","15.2.2019.","16.2.2019","Amsterdam Aerodrom","Rim Aerodrom","30","8000"]],
let3:[["3","6","25.2.2019.","28.2.2019.","Rim Aerodrom","Beograd Aerodrom","30","8000"]],
let4:[["4","8","13.2.2019.","14.2.2019.","Beograd Aerodrom","Moskva Aerodrom","30","13000"]],
let5:[["5","10","1.3.2019.","4.3.2019.","Beograd Aerodrom","New York Aerodrom","30","18000"]]
};
function getParamValue(brojleta) {
var location = decodeURI(window.location.toString());
var index = location.indexOf("?") + 1;
var subs = location.substring(index, location.length);
var splitted = subs.split("&");
for (i = 0; i < splitted.length; i++) {
var s = splitted[i].split("=");
var pName = s[0];
var pValue = s[1];
if (pName == brojleta) {
return pValue;
}
}
}
var brojleta = getParamValue("id");
var item = data.find(item => item[0][0] === brojleta);
var id = item[0][1]
var datumpolaska = item[0][2]
var datumdolaska = item[0][3]
var polazniaerodrom = item[0][4]
var dolazniaerodrom = item[0][5]
var brojsedista = item[0][6]
var cenakarte = item[0][7]
var data1 = data.let1[0];
var data2 = data.let2[0];
var data3 = data.let3[0];
var data4 = data.let4[0];
var data5 = data.let5[0];
/* this is the code for adding data from array to table */
$(document).ready(function(){
var row1cells = $("#row1 td");
var row2cells = $("#row2 td");
var row3cells = $("#row3 td");
var row4cells = $("#row4 td");
var row5cells = $("#row5 td");
for (var index=0; index<8; index++) {
$(row1cells[index]).html(data1[index]);
$(row2cells[index]).html(data2[index]);
$(row3cells[index]).html(data3[index]);
$(row4cells[index]).html(data4[index]);
$(row5cells[index]).html(data5[index]);
}
});
To make your code work you should choose variable data to be an array of arrays instead of an object. Then you can run var item = data.find(item => item[0] === brojleta); and similar operations.
It would look like this:
var data = [["1","2","10.2.2019.","11.2.2019.","Beograd Aerodrom","Amsterdam Aerodrom","30","12000"],
["2","4","15.2.2019.","16.2.2019","Amsterdam Aerodrom","Rim Aerodrom","30","8000"],
["3","6","25.2.2019.","28.2.2019.","Rim Aerodrom","Beograd Aerodrom","30","8000"],
["4","8","13.2.2019.","14.2.2019.","Beograd Aerodrom","Moskva Aerodrom","30","13000"],
["5","10","1.3.2019.","4.3.2019.","Beograd Aerodrom","New York Aerodrom","30","18000"]];
I think you really want this:
Remove the || 3 // test #3 after testing
Try removing the 3 from the input and click search too
var data = {
let1:[["1","2","10.2.2019.","11.2.2019.","Beograd Aerodrom","Amsterdam Aerodrom","30","12000"]],
let2:[["2","4","15.2.2019.","16.2.2019","Amsterdam Aerodrom","Rim Aerodrom","30","8000"]],
let3:[["3","6","25.2.2019.","28.2.2019.","Rim Aerodrom","Beograd Aerodrom","30","8000"]],
let4:[["4","8","13.2.2019.","14.2.2019.","Beograd Aerodrom","Moskva Aerodrom","30","13000"]],
let5:[["5","10","1.3.2019.","4.3.2019.","Beograd Aerodrom","New York Aerodrom","30","18000"]]
};
function getParamValue(brojleta) {
return new URLSearchParams(document.location.search.substring(1)).get(brojleta)
}
function show(item) {
$tr = $("<tr/>"), $tbd = $("#tbd");
$.each(item,function(_,fld) {
$tr.append("<td>"+fld+"</td>");
})
$tr.appendTo($tbd);
}
function showAll() {
Object.keys(data).forEach(function(key) {
show(data[key][0]);
})
}
$(function() {
$("#search").on("click",function() {
$("#tbd").empty();
var brojleta = $("#broj_leta").val();
if (brojleta) show(data["let"+brojleta][0])
else showAll();
});
var brojleta = getParamValue("id") || 3 // test #3
if (brojleta) $("#broj_leta").val(brojleta);
$("#search").trigger("click");
})
th, td { border:1px solid lightgrey; padding: 3px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="broj_leta" /><button id="search">Search</button>
<table>
<thead>
<tr>
<th>id</th>
<th>Datumpolaska</th>
<th>Datumdolaska</th>
<th>Plazniaerodrom</th>
<th>Dolazniaerodrom</th>
<th>Brojsedista</th>
<th>Cenakarte</th>
</tr>
</thead>
<tbody id="tbd">
</tbody>
</table>
You can first filter the data based on ID and then map your required variable to final output array in below code output.
var brojleta = 1;
const mappedarray = Object.entries(data).filter((k,v)=>{return k[0] == "let"+brojleta});
console.log(mappedarray[0][1][0]);
You can use the lodash function find().
This is the same function as Array.find but it works on Object.
https://lodash.com/docs/4.17.11#find

How to push a value in an array

i want to know how can i store data in an array like that in order to do it with push function.
here is the code
var data_array = [];
and data look like that
var my_data = {
"2011":{"name":"Team Leaders","total":93,"drilldown":"true"},
"2012":{"name":"Agents","total":1997,"drilldown":"true"},
"2013":{"name":"Coachs","total":1188,"drilldown":"true"},
"2014":{"name":"Formateurs","total":1188,"drilldown":"true"},
"2015":{"name":"Quality Analysts","total":1188,"drilldown":"true"}
};
any help to change this way of inserting and use push function .
May be this will help,
You can loop through all the keys of the object and push each one into the array
var data_array = [];
var my_data = {
"2011":{"name":"Team Leaders","total":93,"drilldown":"true"},
"2012":{"name":"Agents","total":1997,"drilldown":"true"},
"2013":{"name":"Coachs","total":1188,"drilldown":"true"},
"2014":{"name":"Formateurs","total":1188,"drilldown":"true"},
"2015":{"name":"Quality Analysts","total":1188,"drilldown":"true"}
};
var keysArray = Object.keys(my_data);
keysArray.forEach(function(key, index) {
data_array.push({ key : my_data[key]});
});
console.log(data_array);
Try this (wrap data in curly braces):
data_array.push( {"2011":{"name":"Team Leaders","total":93,"drilldown":"true"} })
I don't know Exactly what do you want. Anyway, I think that It works for you.
var personInfo = new Object();
var my_data = new Object();
personInfo.name = 'Team Leaders';
personInfo.total = 93;
personInfo.drilldown = 'true';
my_data.person1 = personInfo;
my_data.person2 = personInfo;
// confirm
var jsonType = JSON.stringify(my_data);
console.log(jsonType);
I think this is what you need
var data_array = [];
var my_data = {
"2011":{"name":"Team Leaders","total":93,"drilldown":"true"},
"2012":{"name":"Agents","total":1997,"drilldown":"true"},
"2013":{"name":"Coachs","total":1188,"drilldown":"true"},
"2014":{"name":"Formateurs","total":1188,"drilldown":"true"},
"2015":{"name":"Quality Analysts","total":1188,"drilldown":"true"}
};
var data_keys= Object.keys(my_data);
data_keys.forEach(function(key, index) {
var obj = {};
obj[key] = my_data[key];
data_array.push(obj);
});

Retrieve Fields/Column Names of a Sharepoint List using Javascript

<script type="text/javascript">
function retrieveFieldsOfListView(){
var clientContext = new SP.ClientContext.get_current();
var web = clientContext.get_web();
var list = web.get_lists().getByTitle('pranav_list');
var view = list.get_views().getByTitle('Main');
this.listFields = view.get_viewFields();
clientContext.load(this.listFields);
clientContext.executeQueryAsync(Function.createDelegate(this,
this.onListFieldsQuerySucceeded9), Function.createDelegate(this,
this.onListFieldsQueryFailed));
}
function onListFieldsQuerySucceeded9() {
var fieldsinfo='';
var fieldEnumerator = listFields.getEnumerator();
while (fieldEnumerator.moveNext()) {
var oField = fieldEnumerator.get_current();
var fType = oField.get_fieldTypeKind();
fieldsinfo +='\n '+oField.get_title();
}
alert(fieldsinfo);
}
</script>
I want to show the fields of the view using javascript.
Note: My list name is "pranav_list" and view is "Main".
Help..!
SP.View.viewFields property returns field names but not a Field client object collection.
The following example demonstrates how to print field names from a View:
function retrieveFieldsOfListView(listTitle,viewName){
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(listTitle);
var view = list.get_views().getByTitle(viewName);
var viewFields = view.get_viewFields();
context.load(viewFields);
context.executeQueryAsync(printFieldNames,onError);
function printFieldNames() {
var e = viewFields.getEnumerator();
while (e.moveNext()) {
var fieldName = e.get_current();
console.log(fieldName);
}
}
function onError(sender,args)
{
console.log(args.get_message());
}
}

Categories

Resources