How to update the option by json result in Dart - dart

My option values are download from server. How can I update the option values after server return result?
<select name="book" template iterate="book in books" bind-value="selected">
<option selected="{{selected == book}}">{{book}}</option>
</select>
In .dart
List<String> books= <String>[''];
#observable
String selected = 'Doraemon';
void main() {
var request = HttpRequest.getString(url).then((jstr){
// Parse json
Map data = json.parse(jstr);
print(data['option']['books']);
// Refresh the list, but how to refresh option value?
books.addAll(data['option']['books']);
}

You should wrap the books value in a call to "toObservable". https://www.dartlang.org/web-ui/observables/#observing-collections
List<String> books= toObservable(<String>['']);

Related

Angular 7 - Copying a List returned from SQL into an Array

I would like to convert results from an SQL method to an array so that I can use the filter option on the array in Angular 7.
I am still getting my feet wet in Angular (7) and I'm trying to set up a nested dropdown/select list where the first select list is for "Departments" and the selected value will return a result set for my "DeptTypes" dropdown/select list.
I am currently returning the data by sending the selected value (id) call my "changeData(id: number)" event in the ...component.ts. It successfully returns data, but there is sometimes a problem with the dropdown not always populating. It appears that it is a performance or speed issue due to always making the call to the SQL backend. So, I would like to return the data as an array so that I can use the .filter command, but there seem to be no option for that. So, what would be the best solution to my lil' problem? I was thinking about pushing the returned list into an [] array variable that would then allow me to use "push" but I cannot figure out the coding to do that. If there is a better way, by all means, enlighten me. Thanks.
// the calls in my component.ts
opportunityList() { // this is the for the first <select ...>
this.dashboardService.getOpportunities()
.subscribe((opportunities: Opportunities) => {
this.opportunities = opportunities;
},
error => {
// this.notificationService.printErrorMessage(error);
});
}
typeList(id: number) { // nested <select ...> that needs to populate
this.dashboardService.getTypesByOpportunityId(id)
.subscribe((types: Types) => {
this.types = types;
},
error => {
// this.notificationService.printErrorMessage(error);
});
}
changedata($event) { // called after selecting a value in the 1st <select ...>
// to remove previous selected items from second dropdown
//this.finaldata.splice(0);
// filter items and pass into finaldata
//this.finaldata = this.type2.filter(x => x.areaId == $event.target.value);
this.typeList($event.target.value);
this.finaldata = this.types;
}
// the HTML
<label for="areaId">Departments</label>
<select id="areaId" (change)="changedata($event)" [(ngModel)]="opportunityList" class="form-control">
<option *ngFor="let opp of opportunities" [value]="opp.areaId">{{ opp.areaName }}</option>
</select><br />
<label for="typeId">Department Area Types</label>
<select id="typeId" class="form-control">
<option *ngFor="let typeobj of finaldata" [value]="typeobj.typeId">{{ typeobj.typeName}}</option>
</select>
my ...service.ts
getTypesByDepartmentId(id: number): Observable<Types> {
const headers = new Headers();
headers.append('content-Type', 'application/json');
const authToken = localStorage.getItem('auth_token');
headers.append('Authorization', `Bearer ${authToken}`);
return this.http.get(this.baseUrl + '/dashboard/GetTypesByDepartmentId/' + id, { headers })
.map(response => response.json())
.catch(this.handleError);
}
the controller action
#region api/dashboard/GetTypesByDepartmentId
[HttpGet("{id}")]
public async Task <IActionResult> GetTypesByDepartmentId([FromRoute]int id)
{
// retrieve all revenue types
var model = await (from t in _appDbContext.Type where t.AreaId == id
select new
{
t.TypeId,
t.TypeName
}).ToArrayAsync();
return Ok(model);
}
#endregion
The code above, thru the service.ts returns the results, it is not always populating the "typeId". It's a "hit or miss." Sometimes the data is there and sometimes it's just blank.
I would like to go with returning all of the department area types and using an array and the "filter" command. for example:
this.finaldata = this.typeList.filter(x => x.areaId == event.target.value);
in the component.ts itself or a more proper way to handle this issue since "filter" does not work on this call.
Looks like I get to answer my own question. I can actually filter my returned observable ... the issue was that I was defining a variable that used an interface, reflecting my model. If I remove that and make it "any", I can then push it to an array:
types: any;
type2: Types[] = [];
public finaldata: any[] = [];
typeList() {
this.dashboardService.getTypes()
.subscribe((types: Types) => {
this.types = types;
this.type2.push({ areaId: this.types.areaId, typeId: this.types.typeId, typeName: this.types.typeName, areaName: this.types.areaName });
},
error => {
// this.notificationService.printErrorMessage(error);
});
}
changedata($event) {
// to remove previous selected items from second dropdown
this.finaldata.splice(0);
// filter items and pass into finaldata
this.finaldata = this.types.filter(x => x.areaId == $event.target.value);
}
So, I just call my typeList() in my "ngInit()" and it is taken care of.

missunderstanding mvc default binding

I have multiselect jquery plagin (Choosen) and when I use it in 'Multiple Select' mode I expect in controller next values:
posted string = 'value1,value2...'
really have
posted string = 'value2'
only if I reffer directly to FormCollection I'll get expected values as below:
[HttpPost]
public ActionResult TagSearech(/*string tagSelect*/FormCollection c)
{
// only one value here
// string[] names = tagSelect.Split(',');
// as expected: value1,....
string expectedValue = c['tagSelect'];
return View();
}
I cant understand what might cause this behavior.
EDIT
Here is View:
#using (Html.BeginForm("TagSearech", "Tag"))
{
#Html.DropDownList("tagSelect", Model, new { #class = "chzn-select", data_placeholder = "tag names", multiple = "" })
<input type="submit"/>
}
MVC will attempt to bind the input data on the URL into the model. I haven't seen how Chosen.js posts the data back to the server, but essentially its coming in in the wrong format, so MVC binds the first element it sees to the string Model.
The FormsCollection retrieves all of the data that was posted in the URL, which is why all of your selected values can be seen there.
Did you try changing the incoming model from string to string[], and see if all of the items are bound to the array?

How to retrieve value from linkedhashmap using iterators in Struts2......?

I have function which return LinkedHashMap in Struts2 and i just came to know that we cannot use for loop in struts2 instead we have to use Iterators, and am new to struts
can any on help me to retrieve value from linkedhashmap using iterators, below is how values are lined up in hashmap:
LinkedHashMap<String, ArrayList<String>> topSuppliers = new LinkedHashMap<String, ArrayList<String>>();
while(resultset.next()){
ArrayList<String> innerList = new ArrayList<String>();
String manufId = resultset.getString("manufacturer_id");
String manufLogo = resultset.getString("SUPPLIER_LOGO_IMAGE");
String manufName = resultset.getString("MANUFACTURER_NAME");
String manufURL = resultset.getString("MANUFACTURER_URL");
innerList.add(manufId);
innerList.add(manufLogo);
innerList.add(manufName);
innerList.add(manufURL);
topSuppliers.put(manufName,innerList);
}
return topSuppliers;
And i want to display them in a set of 4 manufacturers:
Set1: 1,2,3,4
Set2: 5,6,7,8
Set3: 9,10,11,12
etc......
Thank you........
You should iterate over List of Map instead of Map of List
Example :
#Getter
private List<Map> listOfMap = Lists.newArrayList();
public String execute() {
while (resultset.next()) {
final Map<String, String> map = Maps.newHashMap();
map.put("manufId", resultset.getString("manufacturer_id"));
map.put("manufLogo", resultset.getString("SUPPLIER_LOGO_IMAGE"));
map.put("manufName", resultset.getString("MANUFACTURER_NAME"));
map.put("manufURL", resultset.getString("MANUFACTURER_URL"));
listOfMap.add(map);
}
return SUCCESS;
}
<s:iterator value="listOfMap">
${manufId}
${manufLogo}
${manufName}
${manufURL}
</s:iterator>
The listOfMap also can use as a dataSource for Struts2 JasperReports Plugin.
You can use s:iterator over a map.
<s:iterator value="topSuppliers">
<s:property value="key" />: <s:iterator value="value" status="status"><s:property /><s:if test="!#status.last">,</s:if></s:iterator>
</s:iterator>
This iterates over the map using Map.Entry and then iterates over your value list using another iterator and iterator status to add "," unless it's the last entry.

Struts2 using Map in select tag

You can easily use a List in struts2 select tag, but is there a way to use Map in tag?? If it is possible please provide a sample code...
thanx !
In my action class
public class MyAction extends ActionSupport {
private Map<String, String> map;
public String execute() throws Exception {
map = new HashMap<String, String>();
map.put("abc", "abc");
map.put("xyz", "xyz");
return SUCCESS;
}
}
For the jsp mapped to success, use some thing like this
<s:select list = "map" name = "name" label = "Name" headerKey="" headerValue = "Enter Value"/>
It depends on what are you trying to do. Lacking details, I can only point you to the docs : the list attribute of the select tag is an ...
Iterable source to populate from. If
the list is a Map (key, value), the
Map key will become the option 'value'
parameter and the Map value will
become the option body.
Below in the same doc there is an example with a (literal, inline) map (Months).

struts2 - optiontransferselect - pass list of integers to the action

I have an optiontransferselect in a form but i dont know how to get the selected items in the rightlist back in my action.
I need to get a list with all the visited countries' ids. i tried in my action List (Integer) countriesVisitedId; but it returns nullPointerException. then i tried Integer id but it returns null.
this is what i have:
s:optiontransferselect
label="Select visited countries"
name="countriesNotVisitedId"
leftTitle="Not visited countries"
rightTitle="Visited Countries"
list="%{countriesNotVisited}"
listKey="id"
listValue="name"
headerKey="countryNotVisitedId"
headerValue="--- Please Select ---"
doubleName="countriesVisitedId"
doubleList="%{countriesVisited}"
doubleHeaderKey="countryVisitedId"
doubleHeaderValue="--- Please Select ---"
doubleListKey="id"
doubleListValue="name" />
how can I get the list with the Integers ids of the visited countries in my action?
I was banging my head on the wall wondering what I was doing wrong. It is pretty simple
doubleName="fields" is the tag field that is returned
public void setFields(String fields) { this is what needs to be in your action class.
The thing that I didn't realise is the elements need to be selected in order to be sent back. Or simple use ajax with in your header
Here's what I tried, it works fine.
Step 1: JSP to select the country from the left hand side into right hand.
<s:optiontransferselect
label="Favourite Characters"
name="leftSide"
id="left"
leftTitle="Left Title"
rightTitle="Right Title"
list="%{countriesNotVisited)"
multiple="true"
headerKey="headerKey"
doubleList="{}"
doubleId="right"
doubleName="rightSide"
doubleHeaderKey="doubleHeaderKey"
doubleMultiple="true" />
Step 2: Javascript code to auto select all data from the right hand side.
function selectall()
{
var list = document.getElementById("right");
for (var i = 0; i < list.options.length; i++)
{
alert(list.options[i].value)
list.options[i].selected = true;
}
var form = document.getElementById("right");
form.submit();
return true;
}
Step 3: call this function on submit, from the JSP side.
<s:submit id="submitid" value="Submit" action="insert" onclick="selectall()"/>
Step 4: In the action, make the getters and setters of object names of the left and right sides take strings and not string arrays.
private String leftSide;
private String rightSide;
public String getLeftSide() {
return leftSide;
}
public String getRightSide() {
return rightSide;
}
public void setRightSide(String rightSide) {
this.rightSide = rightSide;
}
public void setLeftSide(String leftSide) {
this.leftSide = leftSide;
}
Now if you try to print a value in the action, you will get values:
System.out.println("right side list " + ad.getRightSide());
In your action:
public void setCountriesVisitedId(String[] countriesVisitedId) {
this.countriesVisitedId = countriesVisitedId;
}

Resources