How to submit multiple Line Items in Struts 2? - html-table

I do have an Purchase request form, which dynamically creates row for ItemName, quantity, specification, unit of measurement.
I do have a one button called "Add item", which dynamically creates new rows.
When I submit this form how do I get it into Action class in Struts2.
JSP:
<table id="itemDetails" width="100%">
<tr width="100%" cellpadding="0" cellspacing="0" border="1" >
<th ><center>+</center></th>
<th >Item</th>
<th >Specification</th>
<th >Quantity</th>
<th >Unit Of Measurement</th>
<th >Operations</th>
</tr>
<s:iterator value="id" status="ctr" >
<tr>
<td width="5%"><input type="checkbox" name="rdel" ><br><br></td>
<td width="30%" ><input type="text" name="id[%{#ctr.index}].itemname" /></td>
<td width="30%"><input type="text" name="id[%{#ctr.index}].specification" ></td>
<td width="20%"><input type="text" name="id[%{#ctr.index}].quantity" ></td>
<td width="5%"><input type="text" name="id[%{#ctr.index}].uom" ></td>
<td width="10%"><a href="#" >Delete</a></td>
</tr>
</s:iterator>
</table>
Javascript for dynamic row creation:
<SCRIPT language="javascript">
function addRow(itemDetails) {
var table = document.getElementById(itemDetails);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var counts=rowCount-1;
var cell1 = row.insertCell(0);
var check = document.createElement("input");
check.type = "checkbox";
check.name="rdel";
cell1.appendChild(check);
var cell2 = row.insertCell(1);
var item = document.createElement("input");
item.type = "text";
item.name="id.item";
cell2.appendChild(item);
var cell3 = row.insertCell(2);
var specification = document.createElement("input");
specification.type = "text";
specification.name="id.specification";
cell3.appendChild(specification);
var cell4 = row.insertCell(3);
var quantity = document.createElement("input");
quantity.type = "text";
quantity.name="id.quantity";
cell4.appendChild(quantity);
var cell5 = row.insertCell(4);
var uom = document.createElement("input");
uom.type = "text";
uom.name="id.uom";
cell5.appendChild(uom);
var cell6 = row.insertCell(5);
var operations = document.createElement("a");
operations.setAttribute("href","#");
operations.innerText="Delete";
cell6.appendChild(operations);
}
</SCRIPT>
Action class method:
private List<ItemDetails> id;
public List<ItemDetails> getId(){
return this.id;
}
public void setId(List<ItemDetails> id) {
this.id = id;
}
public String savePurchaseRequest(){
try{
setId(getId());
for(ItemDetails itemdetails:id ) {
System.out.println( itemdetails.getItemname() + ":" + itemdetails.getSpecification() +":"+ itemdetails.getQuantity()+ ":"+ itemdetails.getUom() );
}
}catch(Exception e){
System.out.println("Exception:"+e);
}
return SUCCESS;
}
and ItemDetails class:
public class ItemDetails implements java.io.Serializable {
private String itemname;
private String specification;
private String quantity;
private String uom;
public ItemDetails() {
}
public ItemDetails(String itemname, String specification, String quantity, String uom) {
this.itemname = itemname;
this.specification = specification;
this.quantity = quantity;
this.uom = uom;
}
}
public String getItemname() {
return this.itemname;
}
public void setItemname(String itemname) {
this.itemname = itemname;
}
public String getSpecification() {
return this.specification;
}
public void setSpecification(String specification) {
this.specification = specification;
}
public String getQuantity() {
return this.quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getUom() {
return this.uom;
}
public void setUom(String uom) {
this.uom = uom;
}
}

you was almost there.
Just change the Javascript part where you assign the name attribute, including the index exactly as you do in the iteration:
item.name="id.item";
specification.name="id.specification";
// ecc...
must become
item.name="id["+counts+"].itemname";
specification.name="id["+counts+"].specification";
And you will be good.

It looks like you set your model items from another page. Try setting them to another variable than id, something like idOutput or so, I had problems myself before when trying to access a field via a getter when this field got set before, although I don't know why this was the case.
The model object (ItemDetails) needs public getters ( like getItemname() ) , so the JSP can read them.

You need to put correct names in the JavaScript, so that OGNL is able to handle them properly and apply values when you submit the form.
To submit newly added row you need to use only these names on the row you've being submitted.

Related

ASP.NET MVC: drop down list display everything and also display alone

I currently display each category individually, but I want to make it possible to view them all together.
Here in the screenshot, I show each category separately, but I want to add another All option that will show me all the animals in all the categories
My repository:
public async Task<IEnumerable<Animal>> SelectAnimalsById(int id)
{
var animal = _context.Animals
.Include(a => a.Category)
.Where(c => c.Category!.CategoryId == id);
return await animal.ToListAsync();
}
public DbSet<Category> GetCategories()
{
var category = _context.Categories;
return category;
}
My controller:
// Displays the animals by category using the Selectlist
public async Task<IActionResult> Commands(int id = 1)
{
var petShopDbContext = await _animalRepository.SelectAnimalsById(id);
ViewBag.Category = new SelectList(_catalogRepository.GetCategories(), "CategoryId", "Name", id);
return View(petShopDbContext);
}
My view:
#model IList<PetShop.Data.Models.Animal>
<label>Please select a category:</label>
<select asp-items="ViewBag.Category" onchange="location.href='/Admin/Commands/'+this.value" id="DesignSelect"></select>
<table id="Table">
<thead>
<tr>
<th><label asp-for="#Model[0].PhotoUrl"></label></th>
<th><label asp-for="#Model[0].Name"></label></th>
<th><label asp-for="#Model[0].Category.Name"></label></th>
<th><label asp-for="#Model[0].Description"></label></th>
<th><label asp-for="#Model[0].BirthDate"></label></th>
<th>Edit Animal</th>
<th>Delete Animal</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model!) {
<tr>
<td><img src="~/Images/#item.PhotoUrl" id="ManagerImage"></td>
<td>#item.Name</td>
<td>#item.Category!.Name</td>
<td>#item.Description</td>
<td>#Html.DisplayFor(model => item.BirthDate)</td>
<td><a asp-action="EditAnimal" asp-route-id="#item.AnimalId"><input type="submit" value="Edit" id="DesignButton"></a></td>
<td><a asp-action="DeleteAnimal" asp-route-id="#item.AnimalId"><input type="submit" value="Delete" id="DesignButton"></a></td>
</tr>
}
</tbody>
</table>
image:
One way is that you can change your code in repository like below:
public async Task<IEnumerable<Animal>> SelectAnimalsById(int id)
{
List<Animal> data= new List<Animal>();
var animal = _context.Animal
.Include(a => a.Category);
if (id != 0)
{
data= await animal.Where(c => c.Category!.CategoryId == id).ToListAsync();
}
else
{
data= await animal.ToListAsync();
}
return data;
}
Another way is that you can change your action code like below:
public async Task<IActionResult> Commands(int id = 1)
{
//add this condition
//if id=0, return all the animals with all the categories
if(id==0)
{
return View(_context.Animal.Include(a => a.Category).ToList());
}
//keep the same.....
var petShopDbContext = await _animalRepository.SelectAnimalsById(id);;
ViewBag.Category = new SelectList(_catalogRepository.GetCategories(), "CategoryId", "Name", id);
return View(petShopDbContext);
}
Then change your view like below:
<select asp-items="ViewBag.Category" onchange="location.href='/Admin/Commands/'+this.value" id="DesignSelect">
<option value="0">ALL</option> //add this option
</select>
You could conditional add the where clause in your repository...
var animal = _context.Animals
.Include(a => a.Category);
if(id != 0)
{
animal.Where(c => c.Category!.CategoryId == id);
}
return await animal.ToListAsync();

HTML Table search on the third column using JavaScript

I am trying to search any employee status exist with IsProtected in the tabl empTable. if any row exist , then the variable ProtectedIsfound must be true
<table id="empTable" >
<tr>
<th>
Employee Name
</th>
<th>
Designation
</th>
<th>
Status
</th>
</tr>
for (i = 0; i < Model.attendanceLogList.Count; i++)
{
<tr>
<td>#Model.attendanceLogList[i].EmployeeName</td>
<td>#Model.attendanceLogList[i].Designation</td>
<td>#Model.attendanceLogList[i].IsProtected</td> // it is boolean in model
</tr>
}
</table>
<script>
var ProtectedIsfound = True // if any record exist with the value is Protected in the column status in the table empTable
</script>
I am trying to search any employee status exist with IsProtected in
the tabl empTable. if any row exist , then the variable
ProtectedIsfound must be true
Do you mean for each row, if the IsProtected is true, the ProtectedIsFound must be true? If that is the case, please refer to the following methods:
Using JavaScript or JQuery method: Loop through the table rows and cells and check if the IsProtected is true, then, based on the result to change the ProtectedIsFound value.
#*JQuery reference*#
<script src="~/lib/jquery/dist/jquery.js"></script>
<script type="text/javascript">
var ProtectedIsfound = false // default value.
//JavaScript method:
document.addEventListener("DOMContentLoaded", function (event) {
//loop through the tr and td, then based on the IsProtected value to change the ProtectedIsFound value.
var trlist = document.getElementById("empTable").getElementsByTagName("tr");
for (var i = 1; i < trlist.length; i++) {
if (trlist[i].getElementsByTagName("td")[2].innerText.toLowerCase() == "true") {
ProtectedIsfound = true;
break;
}
}
console.log(ProtectedIsfound);
});
//JQuery script
$(function () {
$("#empTable").find("tr:not(:first-child)").each(function (index, item) {
if ($(item).find("td")[2].innerText.toLowerCase() == "true") {
ProtectedIsfound = true;
return false;
}
});
console.log(ProtectedIsfound);
});
</script>
Using Where and Select statement, code as below:
<script type="text/javascript">
var ProtectedIsfound = #Model.attendanceLogList.Where(c => c.IsProtected ==true).Select(c=>c).ToList().Count > 0 ? true : false;
console.log(ProtectedIsfound);
</script>
The Html page elements as below (Asp.net core Razor page application):
#page
#model RazorWebApplication5.Pages.HtmlTableModel
#{
}
<table id="empTable">
<tr>
<th>
Employee Name
</th>
<th>
Designation
</th>
<th>
Status
</th>
</tr>
#for (var i = 0; i < Model.attendanceLogList.Count; i++)
{
<tr>
<td>#Model.attendanceLogList[i].EmployeeName</td>
<td>#Model.attendanceLogList[i].Designation</td>
<td>#Model.attendanceLogList[i].IsProtected</td> #*// it is boolean in model*#
</tr>
}
</table>
.cshtml.cs file:
public class HtmlTableModel : PageModel
{
public List<AttendanceLog> attendanceLogList { get; set; }
public void OnGet()
{
//initial data
attendanceLogList = new List<AttendanceLog>()
{
new AttendanceLog(){ EmployeeName="Tom", Designation="A", IsProtected=false},
new AttendanceLog(){ EmployeeName="Jack", Designation="B", IsProtected=false},
new AttendanceLog(){ EmployeeName="Lucy", Designation="CC", IsProtected=true},
new AttendanceLog(){ EmployeeName="Daive", Designation="D", IsProtected=false},
new AttendanceLog(){ EmployeeName="Hanke", Designation="E", IsProtected=false}
};
}
}
public class AttendanceLog
{
public string EmployeeName { get; set; }
public string Designation { get; set; }
public bool IsProtected { get; set; }
}
Test result:
Change the for loop into:
"for (i = 0; i <= Model.attendanceLogList.Count; i++)", it should count up to the total number of the List.
Not sure what library you're using in the script, but instead of:
var ProtectedIsfound = True, it should state
You need a dedicated class name to the so you can refer it in the script
"bool ProtectedIsFound:"
It should be set to true by default.
foreach(emp in Model.attendanceLogList){
if (emp.IsProtected){
{here you will need to append the value in the Status column}
return true; }
else
return;
}

Wicket dynamicly add data from database to page

I'm trying to add some data into page from database, after applying "filter"
After submit form, candidate list is update and I want to push this changes into page.
How can I do this in wicket ?
.java file
public class SearchCandidate extends WebPage {
private SearchCandidateModel searchCandidateModel = new SearchCandidateModel();
private List<CandidateEntity> candidate = new ArrayList();
public SearchCandidate(PageParameters p) {
super(p);
final TextField<String> firstName = new TextField<>("first_name", new PropertyModel<String>(searchCandidateModel, "firstName")); //Filter
final DataView dataView = new DataView("simple", new ListDataProvider(candidate)) {
public void populateItem(final Item item) {
final CandidateEntity user = (CandidateEntity) item.getModelObject();
item.add(new Label("firstName", user.getFirstName()));
}
};
Form<?> form = new Form<Void>("step1") {
#Override
protected void onSubmit() {
candidate = databse.findCandidate(searchCandidateModel.getFirstName());
//UPDATE TABLE
}
};
form.add(firstName);
add(form);
add(dataView);
}
}
html file:
<form wicket:id="step1">
<input wicket:id="first_name" type="text" size="30"/>
</form>
<table cellspacing="0" class="dataview">
<tbody>
<tr wicket:id="simple">
<td><span wicket:id="name">Test ID</span></td>
</tr>
</tbody>
</table>
You can make you DataProvider - dynamic:
new ListDataProvider() {
#Override protected List getData() {
if (noFilter) return emptyList
else return database.getList(filter)
}
}
This way the provider will always load the data according to your data filter.
For more information about static vs. dynamic models/providers check:
https://cwiki.apache.org/confluence/display/WICKET/Working+with+Wicket+models#WorkingwithWicketmodels-DynamicModels

MVC4 No update on selchange DropDownList Postback

After I have changed selected item in my DropDownList everything works fine. But the view doesnt show the newly selected item (value) in the view.
In my code there is #Model.Name What is wrong? I have already spent do many hours on this problem!
My controller looks like this:
//
// GET: /Province/
public ActionResult Test()
{
ModelState.Clear();
var items = _ProvinceService.GetAll();
ViewBag.Lista = new SelectList(items, "Id", "Name", -1);
var province = _LandskapService.FindByName("xyz");
return View("Test", province);
}
// POST /Province/Test
[HttpPost]
public ActionResult Test(int provinceId)
{
if (ModelState.IsValid)
{
ModelState.Clear();
var model = _ProvinceService.GetAll();
var province = _ProvinceService.FindById(provinceId);
ViewBag.Lista = new SelectList(model, "Id", "Name", province.Id);
return View("Test", province);
}
else
{
return View();
}
}
And here is the view:
#Html.DropDownList("dropDownList3", (SelectList)ViewBag.Lista, "-- select province", new { onchange = "UpdateProvince()" })
<table style="border-collapse:collapse">
<tr>
<th style="width:200px">Name</th>
</tr>
<tr>
<td> #Model.Name </td> Here is the problem: #Model.Name is correct but the view dont show it. Old value is displayed. But debugger shows right value (the selected value).
</tr>
function UpdateProvince() {
alert($('#dropDownList3').val());
var SelCat = $("#dropDownList3").val();
var text = $("#dropDownList3 option:selected").text();
var value = $("#dropDownList3 option:selected").val();
if (SelCat != 0) {
var url = '#Url.Action("Test", "Province")';
// $.get(url, {provinceId : value});
$.post(url, { provinceId: value });
}
}

Templated control in ektron

I have tried to retrieve the taxonomy list using taxonomy tree, in edit i am selecting the taxonomy and getting TaxonomyID,by using the taxonomyID i want to display the data using taxonomy filters using templated control.I am unable to retrive the data.I am attaching HTML and Code what i have done,So please help me out for the solution.
<asp:View ID="View" runat="server">
<asp:Label ID="lblID" runat="server"></asp:Label>
<CMS:Directory CssClass="taxList" ID="TaxonomySummary1" EnableAjax="true" runat="server"
EnablePaging="false" />
<ektron:ContentModelSource ID="cntModelSourcs" runat="server" OrderByField="DateCreated"
OrderByDirection="Descending">
<TaxonomyFilters>
<ektron:ContentTaxonomyFilter Operator="Contains" ID="taxFilter" runat="server" />
</TaxonomyFilters>
<ContentFilters>
<ektron:ContentFilter Field="Id" Operator="EqualTo" Value="" />
</ContentFilters>
</ektron:ContentModelSource>
<ektron:ContentView ID="ContentView1" runat="server" ModelSourceID="cntModelSourcs"
EktronCustomTemplate="Ektron_ContentList_Template" >
</ektron:ContentView>
</asp:View>
enter code here
_edit" class="TSWidget">
<div class="ByTaxonomy TSTabPanel">
<div style="height: 150px; overflow: auto;">
<UC:TaxonomyTree ID="TaxonomyTree1" runat="server" />
</div>
<hr />
</div>
<div class="ByProperty TSTabPanel">
<table style="width: auto;">
<tr>
<td class="label">
<%=m_refMsg.GetMessage("lbl taxonomy id:")%>
</td>
<td>
<asp:TextBox ID="taxonomyid" CssClass="folderid" runat="server" Style="width: auto;"></asp:TextBox>
</td>
</tr>
<tr>
<td class="label">
<%=m_refMsg.GetMessage("lbl taxonomy path:")%>
</td>
<td>
<asp:Label ID="taxonomypath" CssClass="taxonomypath" runat="server"></asp:Label>
</td>
</tr>
</table>
</div>
<div class="TSEditControls">
<asp:Button ID="CancelButton" CssClass="TSCancel" runat="server" Text="Cancel" OnClick="CancelButton_Click" />
<asp:Button ID="SaveButton" CssClass="TSSave" runat="server" OnClick="SaveButton_Click" Text="Save" />
</div>
</div>
</asp:View>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ektron.Cms;
using Ektron.Cms.Widget;
using Ektron.Cms.Common;
using Ektron.Cms.API;
using Ektron.Cms.Organization;
using Ektron.Cms.Framework.Organization;
using System.Text;
using Ektron.Cms.Search.Expressions;
using Ektron.Cms.Search;
using Ektron.Cms.Framework;
public partial class widgets_Content_TaxonomyFilter : System.Web.UI.UserControl,IWidget
{
# region Properties
protected string appPath = "";
private Ektron.Cms.CommonApi _commonAPI = new CommonApi();
private long _taxonomyid;
public string TaxonomySelected = "selected";
public string PropertySelected = "selected";
public string m_strTaxonomyPath = "/";
private string _taxonomypath;
[WidgetDataMember(0)]
public long TaxonomyId { get { return _taxonomyid; } set { _taxonomyid = value; } }
[WidgetDataMember("")]
public string TaxonomyPaths { get { return _taxonomypath; } set {
_taxonomypath = value; } } private IWidgetHost _host;
protected ContentAPI m_refContentApi = new ContentAPI();
protected EkMessageHelper m_refMsg;
#endregion
# region Page Load
protected void Page_Load(object sender, EventArgs e)
{
taxFilter.Value = TaxonomyId.ToString();
ContentView1.DataBind();
}
#endregion
#region Page Init
protected void Page_Init(object sender, EventArgs e)
{
m_refMsg = m_refContentApi.EkMsgRef;
CancelButton.Text = m_refMsg.GetMessage("btn cancel");
SaveButton.Text = m_refMsg.GetMessage("btn save");
_host = Ektron.Cms.Widget.WidgetHost.GetHost(this);
_host.Title = "Templated Control";
_host.Edit += new EditDelegate(EditEvent);
_host.Maximize += new MaximizeDelegate(delegate() { Visible = true; });
_host.Minimize += new MinimizeDelegate(delegate() { Visible = false; });
_host.Create += new CreateDelegate(delegate() { EditEvent(""); });
_host.ExpandOptions = Expandable.ExpandOnEdit;
appPath = _commonAPI.AppPath;
Load += new EventHandler(delegate(object PreRenderSender, EventArgs Evt) { if
(ViewSet.GetActiveView() != Edit) SetTaxonomySummary(); });
ViewSet.SetActiveView(View);
}
protected void SetTaxonomySummary()
{
if (TaxonomyId > 0)
{
lblID.Text = Convert.ToString(taxFilter.Value);
}
}
#endregion
#region EditEvent
void EditEvent(string settings)
{
try
{
string sitepath = _commonAPI.SitePath;
string webserviceURL = sitepath + "widgets/taxonomysummary/TSHandler.ashx";
JS.RegisterJSInclude(this, JS.ManagedScript.EktronJS);
Ektron.Cms.API.JS.RegisterJSInclude(this,
Ektron.Cms.API.JS.ManagedScript.EktronJQueryClueTipJS);
JS.RegisterJSInclude(this, JS.ManagedScript.EktronScrollToJS);
JS.RegisterJSInclude(this, sitepath + "widgets/taxonomysummary/behavior.js",
"TaxonomySummaryWidgetBehaviorJS");
if (TaxonomyId > 0)
{
TaxonomySelected = "";
JS.RegisterJSBlock(this, "Ektron.PFWidgets.TaxonomySummary.webserviceURL =
\"" + webserviceURL + "\";
Ektron.PFWidgets.TaxonomySummary.setupAll();
Ektron.PFWidgets.TaxonomySummary.SetTabs.init()
; ", "EktronPFWidgetsTSInit");
}
else
{
PropertySelected = "";
JS.RegisterJSBlock(this, "Ektron.PFWidgets.TaxonomySummary.webserviceURL =
\"" + webserviceURL + "\";
Ektron.PFWidgets.TaxonomySummary.setupAll(); ", "EktronPFWidgetsTSInit");
}
Css.RegisterCss(this, sitepath + "widgets/taxonomysummary/TSStyle.css",
"TSWidgetCSS");
ViewSet.SetActiveView(Edit);
//set taxonomy path
Ektron.Cms.API.Content.Taxonomy _apiTaxonomy = new
Ektron.Cms.API.Content.Taxonomy();
Ektron.Cms.TaxonomyRequest taxRequest = new Ektron.Cms.TaxonomyRequest();
taxRequest.TaxonomyId = TaxonomyId;
taxRequest.IncludeItems = false;
taxRequest.TaxonomyLanguage = _apiTaxonomy.ContentLanguage;
Ektron.Cms.TaxonomyData taxData = _apiTaxonomy.LoadTaxonomy(ref taxRequest);
if (!(taxData == null || string.IsNullOrEmpty(taxData.Path)))
{
taxonomypath.Text = taxData.Path;
m_strTaxonomyPath = taxData.Path;
}
else
{
m_strTaxonomyPath = "";
}
}
catch (Exception e)
{
ViewSet.SetActiveView(View);
}
}
#endregion
#region Button Events
protected void CancelButton_Click(object sender, EventArgs e)
{
ViewSet.SetActiveView(View);
}
protected void SaveButton_Click(object sender, EventArgs e)
{
int taxID = Convert.ToInt32(taxonomyid.Text);
TaxonomyId = taxID;
taxFilter.Value = TaxonomyId.ToString();
SetTaxonomySummary();
_host.SaveWidgetDataMembers();
ViewSet.SetActiveView(View);
}
#endregion
public EventArgs e { get; set; }
}
If I understand your question correctly, you have the taxonomy id and want to display all the content within that taxonomy. If that is not what you are after, then please clarify your question, and I'll try to help as best I can.
I find that the added baggage that comes along with a widget can sometimes make it hard to test for correct API and server control usage. For that reason, I'd recommend starting off with a simple ASPX page.
<ektron:ContentModelSource ID="contentModelSource" runat="server">
</ektron:ContentModelSource>
<ektron:ContentView ID="ContentView1" runat="server" ModelSourceID="contentModelSource" EktronCustomTemplate="Ektron_ContentList_Template">
</ektron:ContentView>
Normally, the examples you'll find for the templated server controls show the declarative syntax for setting the filters, where you put them right into the ASPX markup - right inside the ContentModelSource control. Something like:
<TaxonomyFilters>
<ektron:ContentTaxonomyFilter Field="Id" Operator="EqualTo" Value="208" />
</TaxonomyFilters>
(More examples here and here.)
But for what it sounds like you want to accomplish, you need to define the filters via code. This code does just that:
protected long TaxonomyId
{
get
{
long id;
long.TryParse(Request.QueryString["id"], out id);
return id;
}
}
protected bool IsRecursive
{
get
{
bool recursive;
bool.TryParse(Request.QueryString["recursive"], out recursive);
return recursive;
}
}
protected void Page_Init(object sender, EventArgs e)
{
if (TaxonomyId > 0)
{
if (IsRecursive)
{
var tm = new TaxonomyManager();
var td = tm.GetItem(TaxonomyId);
if (td != null)
{
var pathFilter = new ContentTaxonomyFilter();
pathFilter.Field = ContentTaxonomyProperty.Path;
pathFilter.Operator = CriteriaFilterOperator.StartsWith;
pathFilter.Value = td.Path;
contentModelSource.TaxonomyFilters.Add(pathFilter);
}
}
else
{
var filter = new ContentTaxonomyFilter();
filter.Field = ContentTaxonomyProperty.Id;
filter.Value = TaxonomyId.ToString();
filter.Operator = CriteriaFilterOperator.EqualTo;
contentModelSource.TaxonomyFilters.Add(filter);
}
}
}
A couple of things to note:
The TaxonomyId is a property. I did this so that there would be an easy point of comparison between this simple ASPX page and a custom widget where your property would be decorated with the WidgetDataMember attribute.
The code is in the Page_Init event handler. That is important. Page_Load is too late in the page's lifecycle. I assume this would also be true in the context of a widget.
My code for when IsRecursive == true is not necessarily optimized. You could get reasonable performance by turning on caching in the FrameworkAPI, but the idea of calling the api to get the taxonomyData and then using that to set the filter for the content seems a little off. Ideally, the ContentTaxonomyFilter would have a "Recursive" property.