Passing list of objects from controller to View in MVC4 - javascript

I am new to ASP/MVC and as part of that started learning using a simple app.
I have a collection of objects as below in the controller
public ActionResult loadimage(String FQDN, String trange)
{
List<geo_crd> Geo_crd = new List<geo_crd>();
//more logic
foreach (ToDoItem T in query1)
{
IEnumerable<GeoItem> query2 = (from b in db1.GeoItems
where b.DNS_server_address == T.DNS_server_address
select b);
foreach (GeoItem X in query2)
{
Geo_crd.Add(new geo_crd(X.DNS_latitude, X.DNS_longitude, 1));
}
}
return View(Geo_crd);
}
Geo_crd is in models as follows
namespace ToDoApp.Models
{
public class geo_crd
{
private Decimal _geo_lat;
private Decimal _geo_long;
private int _status_flag;
public geo_crd(Decimal x, Decimal y, int z)
{
_geo_lat = x;
_geo_long = y;
_status_flag = z;
}
public Decimal geo_lat
{
get { return _geo_lat; }
set { _geo_lat = value; }
}
public Decimal geo_long
{
get { return _geo_long; }
set { _geo_long = value; }
}
public int status_flag
{
get { return _status_flag; }
set { _status_flag = value; }
}
}
}
I am receiving in the views as follows
#model IEnumerable <ToDoApp.Models.geo_crd>
// more code here
<script type="text/javascript">
#foreach (var item in Model){
<spam><li> #item.geo_lat </li></spam>
<span> <li> AddLocationPin(#item.geo_lat, #item.geo_long, null, 'place 1');</li> </span>
}
</script>
the issue I am having is , the server is not sending the AddlocatioPin , it is just ignoring it I guess.
am i doing something really stupid ?
please help

You should not wrap html tags with script.
Start and end tags, also their order must match in html. Also you should read more about HTML ul tag
Correct view would be
#model IEnumerable <ToDoApp.Models.geo_crd>
//more code here
<ul>
#foreach (var item in Model)
{
<li><span>#item.geo_lat </span></li>
<li><span>AddLocationPin(#item.geo_lat, #item.geo_long, null, 'place 1'); </span> </li>
}
</ul>

Related

How to run stand-alone Javascript in Blazor

How can I run some Javascript functions in a Blazor app, without using the JS interop or jQuery? Just plain old Javascript functions that interact with the DOM, independently of Blazor.
I added my script right before the closing </body> tag:
<script src="app.js"></script>
And in app.js I have the following:
var elements = document.querySelectorAll(".some-element");
elements.forEach(function (element) {
element.addEventListener("click", (e) => {
alert("Hello");
});
});
Of course the selector finds no element. I'm guessing they aren't yet present in the DOM at that point? How can I run that script without using the JS interop or jQuery?
If your okay with using jquery you can use an on handler, which will apply to dynamically added elements
$("body").on("click", ".some-element", function(){
alert("Hello");
});
You can do natively too, but seems sketchy IMHO:
document.querySelector('body').addEventListener('click', function(event) {
if (event.target.className.toLowerCase() === 'some-element') {
alert("Hello");
}
});
Note you have weird javascripty things to worry about now like z-index if the click event actually gets up to the body, but it should work for simple stuff.
Main question is WHY would you want to do this in Blazor - whole point is you can use C# events instead you crazy person!!
Create a page like this:
<div height="#($"{Height}px")" width="#($"{Width}px")">
Test
</div>
<button #onclick="DoubleSize">Double Size</button>
#code
{
public int Width { get; set; } = 50;
public int Height { get; set; } = 50;
private void DoubleSize()
{
Width = Width * 2;
Height = Height * 2;
}
}
On render the height and width are 50px:
Then you click the Button, and they change to 100px:
Similarly with CSS if that's what you were talking about:
<div style="width: #($"{Width}px"); height: #($"{Height}px")">
Test
</div>
This is interacting with the properties of the DOM elements without using Javascript... you can do this with any property. You don't need to use Javascript - you just bind them to your properties in C#...
You shouldn't need to 'retrieve the final properties of the rendered DOM elements' as you should be controlling them from C# and not worrying about the DOM
I'm pretty new in Blazor, so sorry if it's not the correct way to do it in Balzor. But I think that you need always use JS interop to use JavaScript function. You want to execute some script, but the question is: when do you want to execute the script? I imagine you want to execute an action after navigate to a page, after make a click in a button... and all this events happens in Blazor
If you ask about relationate an blazor element with the doom you need use #ref
A little example. You create a .js like
var auxiliarJs = auxiliarJs || {};
auxiliarJs.getBoundingClientRect = function (elementRef) {
let result = elementRef? elementRef.getBoundingClientRect():
{left: 0,top: 0,right: 0,bottom: 0,x: 0,y: 0,width: 0,height: 0 };
return result;
}
auxiliarJs.executeFunction = function (elementRef, funciones) {
let res = null;
try {
if (Array.isArray(funciones)) {
functiones.forEach(funcion => {
elementRef[funcion]()
});
}
else
res = elementRef[funciones]();
}
catch (e) { }
if (res)
return res;
}
auxiliarJs.setDocumentTitle = function (title) {
document.title = title;
};
And a service.cs with his interface
public interface IDocumentService
{
Task<ClientRect> getBoundingClientRect(ElementReference id);
Task setDocumentTitle(string title);
Task<JsonElement> executeFunction(ElementReference id, string funcion);
Task executeFunction(ElementReference id, string[] funciones);
}
public class DocumentService:IDocumentService
{
private IJSRuntime jsRuntime;
public DocumentService(IJSRuntime jsRuntime)
{
this.jsRuntime = jsRuntime;
}
public Dictionary<string, object> JSonElementToDictionary(JsonElement result)
{
Dictionary<string, object> obj = new Dictionary<string, object>();
JsonProperty[] enumerador = result.EnumerateObject().GetEnumerator().ToArray();
foreach (JsonProperty prop in enumerador)
{
obj.Add(prop.Name, prop.Value);
}
return obj;
}
public async Task<ClientRect> getBoundingClientRect(ElementReference id)
{
return await jsRuntime.InvokeAsync<ClientRect>("auxiliarJs.getBoundingClientRect", id);
}
public async Task setDocumentTitle(string title)
{
await jsRuntime.InvokeVoidAsync("auxiliarJs.setDocumentTitle", title);
}
public async Task<JsonElement> executeFunction(ElementReference id,string funcion)
{
var result= await jsRuntime.InvokeAsync<JsonElement>
("auxiliarJs.executeFunction", id, funcion);
return result;
}
public async Task executeFunction(ElementReference id, string[] funciones)
{
await jsRuntime.InvokeVoidAsync("auxiliarJs.executeFunction", id, funciones);
}
}
public class ClientRect
{
public float left{ get; set; }
public float top { get; set; }
public float right { get; set; }
public float bottom { get; set; }
public float x { get; set; }
public float y { get; set; }
public float width { get; set; }
public float height { get; set; }
}
Well, you inject the service as usual in program.cs
public static async Task Main(string[] args){
....
builder.Services.AddSingleton<IDocumentService, DocumentService>();
}
And in your component razor
#inject IDocumentService document
<div #ref="mydiv"></div>
<input #ref="myinput">
<button #onclick="click">click</button>
#code{
private ElementReference mydiv;
private ElementReference myinput;
click(){
ClientRect rect = await document.getBoundingClientRect(mydiv);
document.setDocumentTitle("New Title");
document.executeFunction(myinput 'focus')
}
}
Blazor "overwrites" all attached JS Events during render process
window.attachHandlers = () => {
var elements = document.querySelectorAll(".some-element");
elements.forEach(function (element) {
element.addEventListener("click", (e) => {
alert("Hello");
});
});
and in razor page
protected override void OnAfterRender(bool firstRender)
{
if(firstRender)
{
JSRuntime.InvokeVoidAsync("attachHandlers");
}
}

How to display a enum value using a user-entered int?

I need to do 3 things with the CardsDriver: using the default constructor Card() display a default card. Then, take a user's int and display a Card object using the parameterized constructor Card(int n) (Using mod%). Finally use showDeck() to display all 52 cards. (As you can tell I kinda did this using the enhanced for loops at the end, it works but I do not think it is the best way.)
Would really like some help with at least the second problem. I just need to understand what I need to implement..
package cards;
import java.util.Scanner;
public class CardsDriver
{
private static Scanner keyboard = new Scanner(System.in);
public static void main (String[] args)
{
boolean another;
int n;
Card card = new Card();
do
{
System.out.println("Type a non-negative integer. Type -1 to
stop.");
n = keyboard.nextInt( );
if (n == -1)
{
another = false;
}
else
{
another = true;
}
} while (another == true);
System.out.println("All 52 Cards Follow:");
showDeck( );
}
private static int getNextInt()
{
return keyboard.nextInt();
}
private static void showDeck()
{
for (Face face : Face.values())
{
for (Suit suit : Suit.values())
System.out.println("The " + face + " of " + suit);
}
}
}
and here is my Card class
package cards;
public class Card {
private Face face;
private Suit suit;
public Card() {
face = Face.ACE;
suit = Suit.CLUBS;
}
public Card(Card existingCard) {
this.face = existingCard.face;
this.suit = existingCard.suit;
}
public Card(int n) {
face = Face.values()[n % 13];
suit = Suit.values()[n % 4];
}
public String toString() {
return "the" + face + "of" + suit;
}
}

Comparing Selected DropDown with condition

i am creating a form which can be accessed based on condition in MVC. I have first view with dropdownlist and submit button, i want when the submit button is clicked, the value in dropdownlist is passed and compared with condition set for that value, and if the condition is not ok, it shows alert rather than processing to the form.
Here is my code:
public ActionResult ChooseType()
{
var x = DataAccess.GetEmployee(#User.Identity.Name);
var lists = new SelectList(RuleAccess.GetAllRule(), "ID", "TypeDetail");
ViewBag.CategoryId = lists;
/*rule*/
ViewBag.comp1 = Logic.AnnualToogle(#User.Identity.Name);
if (x.EmpSex == "F" && x.EmpMaritalSt == "NIKAH")
{ ViewBag.comp2 = 1; }
else ViewBag.comp2 = 0;
return View();
}
[HttpGet]
public ActionResult Create(int lv_type)
{
var type = RuleAccess.GetTypeByID(lv_type);
ViewBag.type = type;
var model = new LeaveApplicationViewModels();
model.X = DataAccess.GetEmployee(#User.Identity.Name);
model.C = DataAccess.GetLeaveApp(#User.Identity.Name);
/*disable*/
ViewBag.dis = DataAccess.GetDisabledDate(#User.Identity.Name);
/*max*/
var max= RuleAccess.GetMaxByID(lv_type);
ViewBag.c = max;
if (lv_type == 1)
{
var used = RuleAccess.CountUsedAnnual(#User.Identity.Name);
var rem = max - used;
ViewBag.a = used;
ViewBag.b = rem;
}
else
{
ViewBag.b = max;
}
return View(model);
}
I used the Viewbag.comp 1 & 2 in my view:
<script type="text/javascript">
var x = #ViewBag.comp1;
var y = #ViewBag.comp2;
function validatecreate()
{
var value= document.getElementById("lv_type").value;
if (value==1)
{
if(x==1)
document.getElementById('validatecreate').submit();
else { alert('Action cant be done. You either have another annual leave application in pending status or you have reach the limit of annual leave'); }
}
else if(value==2)
{
if(y==1)
document.getElementById('validatecreate').submit();
else { alert('Action cant be done. You either are Male or Not Married Yet'); }
}
else if(value==3)
{
document.getElementById('validatecreate').submit();
}
else {
document.getElementById('validatecreate').submit();
//alert('Http Not Found');
}
}
#Html.DropDownList(
"lv_type", (SelectList) ViewBag.CategoryId,
"--Select One--",
new{ //anonymous type
#class = "form-control input-sm"
}
)
I feel like im doing it wrong especially because if someone manually put the url with ?lv_type=2, they not validate and can go to the form directly. But i need the value of lv_type bcs i use that in my view. Please Helpp :(
Validation must always be done on the server, and client side validation should only be considered a nice bonus that minimizes the need for to a call to the server. And presenting options in a dropdownlist to a user and then telling them thay can't select that option is an awful user experience. Instead, you should be presenting only those options which are applicable to the user (and delete all the scripts you have shown).
Create an additional method in your RuleAccess class, say GetEmployeeRules(Employee employee) which returns only the rules that are applicable to that employee, for example
public static List<Rule> GetEmployeeRules(Employee employee)
{
// Get the list of all rules
if (employee.EmpSex == "F" && employee.EmpMaritalSt == "NIKAH")
{
// Remove the appropriate Rule from the list
}
.....
// Return the filtered list
}
In addition, you should be using a view model in the view
public class LeaveTypeVM
{
[Required(ErrorMessage = "Please select a leave type")]
public int SelectedLeaveType { get; set; }
public IEnumerable<SelectListItem> LeaveTypeList { get; set; }
}
Then in the ChooseType() method
public ActionResult ChooseType()
{
var employee = DataAccess.GetEmployee(#User.Identity.Name);
var rules = RuleAccess.GetEmployeeRules(employee);
var model = new LeaveTypeVM()
{
LeaveTypeList = new SelectList(rules, "ID", "TypeDetail")
};
return View(model);
}
and in the view
#model LeaveTypeVM
#using (Html.BeginForm())
{
#Html.DropDownListFor(m => m.SelectedLeaveType, Model.LeaveTypeList, "--Select One--", new { #class = "form-control input-sm" }
#Html.ValidationMessageFor(m => m.SelectedLeaveType)
<input type="submit" value="Submit" />
}
and submit to a POST method which allows you to easily return the view if its invalid, or to redirect to the Create method.
[HttpPost]
public ActionResult ChooseType(LeaveTypeVM model)
{
if (!ModelState.IsValid)
{
model.LeaveTypeList = .... // as per GET method
}
return RedirectToAction("Create", new { leaveType = model.SelectedLeaveType });
and in the Create() method
public ActionResult Create(int leaveType)
{
var employee = DataAccess.GetEmployee(#User.Identity.Name);
var rule = RuleAccess.GetEmployeeRules(employee).Where(x => x.ID == leaveType).FirstOrDefault();
if (rule == null)
{
// Throw exception or redirect to an error page
}
var model = new LeaveApplicationViewModels();
....
return View(model);
}
Note your LeaveApplicationViewModels should contain additional properties so that you can avoid all those ViewBag properties and generate a strongly typed view.

Get Object from Objects Laravel

i have two Models, first:
class Tutorial extends Eloquent {
protected $table = 'tutorials';
public function rating()
{
return $this->hasMany('Rating');
}
}
and:
class Rating extends Eloquent {
protected $table = 'ratings';
public $timestamps = false;
public function tutorial()
{
return $this->belongsTo('Tutorial');
}
}
now in my controller i have this:
public function get_index() {
$tutorials = tutorial::orderBy('created_at', 'desc')
->with('rating')
->paginate(25);
return View::make('site/home/index')->with('tutorials', $tutorials);
}
So how do i get all ratings from one tutorial in my View?!
EDIT:
Now i have this:
public function ratings()
{
return $this->hasMany('Rating');
}
public function getRating()
{
// Grab the ratings from this tutorial
$ratings = $this->ratings;
$summedRatings = 0;
// Loop through them all and add them together
foreach($ratings as $rating)
{
console.log($rating->value);
$summedRatings += $rating->value;
}
// Return the calculated average
return $summedRatings / count($ratings);
}
public function get_index() {
$tutorials = Tutorial::with('ratings')
->with('user')
->orderBy('created_at', 'desc')
->paginate(25);
return View::make('site/home/index')->with('tutorials', $tutorials);
}
and in my View:
#foreach($tutorials as $tutorial)
<span>{{$tutorial->rating}}</span>
#endforeach
But all my < span >´s are empty!
UPDATE: if i do this:
#foreach($tutorials as $tutorial)
#foreach($tutorial->ratings as $rate)
<span>{{$rate->value}}</span>
#endforeach
everything is good....So what´s wrong?
Depending on the platform you're site is on you should always use the correct case.
$tutorials = tutorial::orderBy(...) // Wrong
$tutorials = Tutorial::orderBy(...) // Correct
To eager load the ratings you should always declare your 'with' method before anything else.
$tutorials = Tutorial::with('rating')
->orderBy('created_at', 'DESC')
->paginate(25);
This has, for some reason, been left out of the L4 docs.
In your view you can now access the rating with this
foreach($tutorials as $tutorial)
{
echo $tutorial->rating->{rating table column name};
}
First, as far as naming conventions go, to make things easier to understand: The rating() method within your tutorial method should be called ratings(), so when you grab your ratings, it will look better ($tutorial->ratings)
After renaming this, in your view, while looping through the array of $tutorials, you could access the ratings of each one like this:
foreach($tutorials as $tutorial)
{
$ratings = $tutorial->ratings;
}
Which would retrieve the ratings object of each.
What you should know is that you can create properties for your model if you need to return the calculation of the ratings, instead of the ORM objects
For example, if each rating is a number from 1-5 in the ratings table stored in an amount column, you can do this to set the average of each rating as a property:
class Tutorial extends Eloquent {
protected $table = 'tutorials';
public function ratings()
{
return $this->hasMany('Rating');
}
public function getRating()
{
// Grab the ratings from this tutorial
$ratings = $this->ratings;
$summedRatings = 0;
// Loop through them all and add them together
foreach($ratings as $rating)
{
$summedRatings += $rating->amount;
}
// Return the calculated average
return $summedRatings / count($ratings);
}
}
Then in your view, you can echo out the property as if it were part of the database
foreach($tutorials as $tutorial)
{
echo $tutorial->rating;
}

How to create dependant dropndown/selection cell In GWT celltable 2.3?

I am using gwt2.3 celltable.
In my celltable there will be multiple column out of that few columns are dependent.
ex. Name and address columns are dependent
Name and address columns contains my custom selection cells.
In Name column : 1 cell contains jon,tom,steve
when Name cell contains jon then I want to set US & UK in address cell
if user changes Name cell to tom then I want to set india & china in address cell
if user changes Name cell to steve then I want to set japana & bhutan in address cell
I want to change dependent data from address cell when name cells selection changes.
How I can achieve this thing? Any sample code or pointers to do this?
This solution is for GWT 2.5, but it should probably work in 2.3.
I think the best is that you modify your RecordInfo element when you change the selection on the first column. You can do it similar to this in your CustomSelectionCell:
#Override
public void onBrowserEvent(Context context, Element parent, C value, NativeEvent event, ValueUpdater<C> valueUpdater) {
super.onBrowserEvent(context, parent, value, event, valueUpdater);
if (BrowserEvents.CHANGE.equals(event.getType())) {
Xxxxx newValue = getSelectedValueXxxxx();
valueUpdater.update(newValue);
}
}
Then where you use your cell add a fieldUpdater like this, that will update the RecordInfo with the new value and ask to redraw the row:
column.setFieldUpdater(new FieldUpdater<.....>() {
....
recordInfo.setXxxxx(newValue);
cellTable.redrawRow(index);
....
});
This will call the render of the other CustomSelectionCell, in there you will be able to check if the value of the RecordInfo has changed and update the seletion values as needed. Example:
#Override
public void render(Context context, C value, SafeHtmlBuilder sb) {
if (!value.getXxxxx().equals(this.lastValue)) {
this.items = loadItemsForValueXxxx(value.getXxxxx());
}
.... // Your usual render.
}
Be careful when you changed the items to set a default selected item too.
This is my implementation of DynamicSelectionCell.
DynamicSelectionCell allows you to render different options for different rows in the same GWT table.
Use a single DynamicSelectionCell object and use the addOption method to add options for each row. Options are stored in a Map with the Key being the row number.
For each row $i in the table the options stored in the Map for key $i are rendered.
Works on DataGrid, CellTable.
CODE
public class DynamicSelectionCell extends AbstractInputCell<String, String> {
public TreeMap<Integer, List<String>> optionsMap = new TreeMap<Integer, List<String>>();
interface Template extends SafeHtmlTemplates {
#Template("<option value=\"{0}\">{0}</option>")
SafeHtml deselected(String option);
#Template("<option value=\"{0}\" selected=\"selected\">{0}</option>")
SafeHtml selected(String option);
}
private static Template template;
private TreeMap<Integer, HashMap<String, Integer>> indexForOption = new TreeMap<Integer, HashMap<String, Integer>>();
/**
* Construct a new {#link SelectionCell} with the specified options.
*
* #param options the options in the cell
*/
public DynamicSelectionCell() {
super("change");
if (template == null) {
template = GWT.create(Template.class);
}
}
public void addOption(List<String> newOps, int key){
optionsMap.put(key, newOps);
HashMap<String, Integer> localIndexForOption = new HashMap<String, Integer>();
indexForOption.put(ind, localIndexForOption);
refreshIndexes();
}
public void removeOption(int index){
optionsMap.remove(index);
refreshIndexes();
}
private void refreshIndexes(){
int ind=0;
for (List<String> options : optionsMap.values()){
HashMap<String, Integer> localIndexForOption = new HashMap<String, Integer>();
indexForOption.put(ind, localIndexForOption);
int index = 0;
for (String option : options) {
localIndexForOption.put(option, index++);
}
ind++;
}
}
#Override
public void onBrowserEvent(Context context, Element parent, String value,
NativeEvent event, ValueUpdater<String> valueUpdater) {
super.onBrowserEvent(context, parent, value, event, valueUpdater);
String type = event.getType();
if ("change".equals(type)) {
Object key = context.getKey();
SelectElement select = parent.getFirstChild().cast();
String newValue = optionsMap.get(context.getIndex()).get(select.getSelectedIndex());
setViewData(key, newValue);
finishEditing(parent, newValue, key, valueUpdater);
if (valueUpdater != null) {
valueUpdater.update(newValue);
}
}
}
#Override
public void render(Context context, String value, SafeHtmlBuilder sb) {
// Get the view data.
Object key = context.getKey();
String viewData = getViewData(key);
if (viewData != null && viewData.equals(value)) {
clearViewData(key);
viewData = null;
}
int selectedIndex = getSelectedIndex(viewData == null ? value : viewData, context.getIndex());
sb.appendHtmlConstant("<select tabindex=\"-1\">");
int index = 0;
try{
for (String option : optionsMap.get(context.getIndex())) {
if (index++ == selectedIndex) {
sb.append(template.selected(option));
} else {
sb.append(template.deselected(option));
}
}
}catch(Exception e){
System.out.println("error");
}
sb.appendHtmlConstant("</select>");
}
private int getSelectedIndex(String value, int ind) {
Integer index = indexForOption.get(ind).get(value);
if (index == null) {
return -1;
}
return index.intValue();
}
}
Varun Tulsian's answer is very good, but the code is incomplete.
The DynamicSelectionCell stores each rows' options in a map. When the cell updates or renders itself, it matches the row index from your Context to its matching row list in your map.
For posterity, see the simplified and updated version below:
public class DynamicSelectionCell extends AbstractInputCell<String, String> {
interface Template extends SafeHtmlTemplates {
#Template("<option value=\"{0}\">{0}</option>")
SafeHtml deselected(String option);
#Template("<option value=\"{0}\" selected=\"selected\">{0}</option>")
SafeHtml selected(String option);
}
private static Template template;
/**
* key: rowIndex
* value: List of options to show for this row
*/
public TreeMap<Integer, List<String>> optionsMap = new TreeMap<Integer, List<String>>();
/**
* Construct a new {#link SelectionCell} with the specified options.
*
*/
public DynamicSelectionCell() {
super("change");
if (template == null) {
template = GWT.create(Template.class);
}
}
public void addOptions(List<String> newOps, int rowIndex) {
optionsMap.put(rowIndex, newOps);
}
public void removeOptions(int rowIndex) {
optionsMap.remove(rowIndex);
}
#Override
public void onBrowserEvent(Context context, Element parent, String value,
NativeEvent event, ValueUpdater<String> valueUpdater) {
super.onBrowserEvent(context, parent, value, event, valueUpdater);
String type = event.getType();
if ("change".equals(type)) {
Object key = context.getKey();
SelectElement select = parent.getFirstChild().cast();
String newValue = optionsMap.get(context.getIndex()).get(select.getSelectedIndex());
setViewData(key, newValue);
finishEditing(parent, newValue, key, valueUpdater);
if (valueUpdater != null) {
valueUpdater.update(newValue);
}
}
}
#Override
public void render(Context context, String value, SafeHtmlBuilder sb) {
// Get the view data.
Object key = context.getKey();
String viewData = getViewData(key);
if (viewData != null && viewData.equals(value)) {
clearViewData(key);
viewData = null;
}
int selectedIndex = getSelectedIndex(viewData == null ? value : viewData, context.getIndex());
sb.appendHtmlConstant("<select tabindex=\"-1\">");
int index = 0;
try {
for (String option : optionsMap.get(context.getIndex())) {
if (index++ == selectedIndex) {
sb.append(template.selected(option));
} else {
sb.append(template.deselected(option));
}
}
} catch (Exception e) {
System.out.println("error");
}
sb.appendHtmlConstant("</select>");
}
private int getSelectedIndex(String value, int rowIndex) {
if (optionsMap.get(rowIndex) == null) {
return -1;
}
return optionsMap.get(rowIndex).indexOf(value);
}
}
Or you could do something like creating a custom cell, which has methods you can call in the getValue of that particular column
say
final DynamicSelectionCell selection = new DynamicSelectionCell("...");
Column<GraphFilterCondition, String> operandColumn=new Column<GraphFilterCondition, String>(selection) {
#Override
public String getValue(FilterCondition object) {
if(object.getWhereCol()!=null){
((DynamicSelectionCell)this.getCell()).addOptions(new String[]{">","<",">="});
}
if(object.getWhereCondition()!=null){
return object.getWhereCondition().getGuiName();
}
return "";
}
};
This should work I guess.
Also check this other question

Categories

Resources