I am a newbie at Spring and I am writing a rental system for movies. I have a Controller where I can get a list of all movies which are still rented (marked by digit "1" as a status in my Database) and which are already have been returned(marked as "0").
Now currently, when I call the page I see all the rented movies with the current status "1" or "0" as well as already returned movies which can still be returned and have a checkbox (which shouldn't be possible.
My question is, how can I change the HTML in the following way:
The status "1" or "0" changes to "rented" and "returned"
I want to remove the checkbox on all movies which already have been returned.
My code:
#Controller
public class MovieController {
#Autowired
private MovieService movieService;
#GetMapping("/home")
public String home(Model model) {
return "index";
}
#GetMapping("/movieList")
public String listAllMovies(Model model) {
model.addAttribute("listMovies", movieService.findNotRented());
return "movies";
}
#GetMapping("/search")
public String findByOption(Model model, #RequestParam(value = "search") String search,
#RequestParam("options") String options) {
if (options.equals("movie")) {
model.addAttribute("listMovies", movieService.findByName(search));
} else if (options.equals("actor")) {
model.addAttribute("listMovies", movieService.findMovieByActor(search));
} else if (options.equals("genre")) {
model.addAttribute("listMovies", movieService.findMovieByGenre(search));
}
return "movies";
}
#GetMapping("/rentedList")
public String findRentedMovies(Model model) {
model.addAttribute("listMovies", movieService.findRentedMovies());
return "rented";
}
#GetMapping("/rentMovie")
public String rentMovie(Model model, #RequestParam int id) {
model.addAttribute("listMovies", movieService.rentMovie(id));
return "index";
}
#GetMapping("/deleteRentedMovie")
public String deleterentedMovie(Model model, #RequestParam int id) {
model.addAttribute("listMovies", movieService.deleteRentedMovie(id));
return "index";
}
#GetMapping("/rentMovie2")
public String rentMovie2(Model model, #RequestParam("idChecked") List<Integer> id) {
if (id != null) {
for (Integer idInt : id) {
model.addAttribute("listMovies", movieService.rentMovie(idInt));
}
}
return "index";
}
#GetMapping("/deleteRentedMovie2")
public String deleterentedMovie(Model model, #RequestParam("idChecked") List<Integer> id) {
if (id != null) {
for (Integer idInt : id) {
model.addAttribute("listMovies", movieService.deleteRentedMovie(idInt));
}
}
return "index";
}
}
Thymeleaf
<h1>Movie List</h1>
<form action="/deleteRentedMovie2">
<table>
<tr>
<th>Title</th>
<th>Time rented</th>
<th>Status</th>
<th>Select</th>
</tr>
<tr th:each="movie : ${listMovies}">
<td th:text="${movie.title}"></td>
<td th:text="${movie.date}"></td>
<td th:text="${movie.status}"></td>
<td><input type="checkbox" th:name="idChecked" th:value="${movie.id}"></td>
</tr>
</table>
<input type="submit" value="Return Movie">
</form>
Thank you in advance and sorry for my bad English
For the status I would something like:
<td>
<span th:if="${movie.status == 1}">rented</span>
<span th:if="${movie.status == 0}">returned</span>
</td>
You could also use the Elvis operator but it is maybe less readable.
For the checkbox:
<td><input th:unless="${movie.status == 0}" type="checkbox" th:name="idChecked" th:value="${movie.id}"></td>
Related
HI Perhaps someone can point me in the right direction.
I created a paginated list page use the example on the ms site.
https://learn.microsoft.com/en-us/aspnet/core/data/ef-rp/sort-filter-page?view=aspnetcore-5.0
and modified it slightly. I replaced one item with a input box as would like to edit the list and do a bulk save instead on opening every item on a new page to edit it.
but when it click the submit button i get the error.
ArgumentNullException: Value cannot be null. (Parameter 'model')
Microsoft.AspNetCore.Mvc.RazorPages.PageModel.TryValidateModel(object model, string name)
if I bind the property
[BindProperty(SupportsGet = true)]
public PaginatedList<CompanyDataListing> CustomersDisplayList { get; set; }
i get the follow error
ArgumentException: Type 'BizFinder.PaginatedList`1[BizFinder.Data.CompanyDataListing]' does not have a default constructor (Parameter 'type')
and even the paginated list does not render.
My code for the sumbit is as follows.
public PaginatedList<CompanyDataListing> CustomersDisplayList { get; set; }
public async Task<IActionResult> OnPostAsync()
{
if (!TryValidateModel(CustomersDisplayList, nameof(CustomersDisplayList)))
{
return Page();
}
foreach (var item in CustomersDisplayList)
{
if (item.GoogleCategory != "")
{
string cat = item.GoogleCategory;
}
}
return Page();
}
and my html is as follow.
#using (Html.BeginForm(FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<table class="table">
<thead>
<tr>
<th>
<a asp-page="./Index" asp-route-sortOrder="#Model.NameSort"
asp-route-currentFilter="#Model.CurrentFilter">
#Html.DisplayNameFor(model => model.CustomersDisplayList[0].CompanyName)
</a>
</th>
<th>
#Html.DisplayNameFor(model => model.CustomersDisplayList[0].Keywords)
</th>
<th>
<a asp-page="./Index" asp-route-sortOrder="#Model.DateSort"
asp-route-currentFilter="#Model.CurrentFilter">
#Html.DisplayNameFor(model => model.CustomersDisplayList[0].GoogleCategory)
</a>
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.CustomersDisplayList)
{
<tr>
<td>
<input type="hidden" asp-for="CustomersDisplayList[0].Id" />
#Html.DisplayFor(modelItem => item.CompanyName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Keywords)
</td>
<td>
#*#Html.DisplayFor(modelItem => item.GoogleCategory)*#
<input asp-for="CustomersDisplayList[0].GoogleCategory" name="Category1" placeholder="Input your keyword" class="form-control GoogleCategory" autofocus="autofocus" />
<span asp-validation-for="CustomersDisplayList[0].GoogleCategory" class="text-danger"></span>
</td>
<td>
<a asp-page="./Edit" asp-route-id="#item.Id">Edit</a> |
<a asp-page="./Details" asp-route-id="#item.Id">Details</a> |
<a asp-page="./Delete" asp-route-id="#item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
<div asp-validation-summary="All">
<span>Please correct the following errors</span>
</div>
#* #Html.ValidationSummary(true, "", new { #class = "text-danger" })*#
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</div>
}
and the full code base is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BizFinder.Data;
using BizFinder.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
//https://learn.microsoft.com/en-us/aspnet/core/data/ef-rp/sort-filter-page?view=aspnetcore-5.0
namespace BizFinder.Pages.Admin
{
public class ManCatergoryModel : PageModel
{
private readonly ApplicationDbContext _context;
private readonly IConfiguration Configuration;
private readonly IAuthorizationService _authorizationService;
public int PageSize { get; set; } = 10;
// private readonly SchoolContext _context;
public ManCatergoryModel(ApplicationDbContext context, IConfiguration configuration)
{
_context = context;
Configuration = configuration;
}
public string NameSort { get; set; }
public string DateSort { get; set; }
public string CurrentFilter { get; set; }
public string CurrentSort { get; set; }
// public IList<CompanyDataListing> CustomersDisplayList { get; set; }
// [BindProperty(SupportsGet = true)]
public PaginatedList<CompanyDataListing> CustomersDisplayList { get; set; }
public async Task OnGetAsync(string sortOrder,
string currentFilter, string searchString, int? pageIndex)
{
CurrentSort = sortOrder;
NameSort = String.IsNullOrEmpty(sortOrder) ? "CompanyName" : "";
DateSort = sortOrder == "Keywords" ? "date_desc" : "Date";
if (searchString != null)
{
pageIndex = 1;
}
else
{
searchString = currentFilter;
}
CurrentFilter = searchString;
// using System;
IQueryable<CompanyDataListing> CompData = from s in _context.CompanyDataList
where s.GoogleCategory == null
select s;
switch (sortOrder)
{
case "name_desc":
CompData = CompData.OrderByDescending(s => s.CompanyName);
break;
case "Date":
CompData = CompData.OrderBy(s => s.Keywords);
break;
case "GoogleCategory":
CompData = CompData.OrderByDescending(s => s.GoogleCategory);
break;
default:
CompData = CompData.OrderBy(s => s.CompanyName);
break;
}
// var pageSize = Configuration.GetValue("PageSize", 4);
CustomersDisplayList = await PaginatedList<CompanyDataListing>.CreateAsync(
CompData.AsNoTracking(), pageIndex ?? 1, PageSize);
}
public async Task<IActionResult> OnPostAsync(PaginatedList<CompanyDataListing> Datalist)
{
// List < CompanyDataListing > mm = CustomersDisplayList.ToList();
foreach (var item in Datalist)
{
string str = item.GoogleCategory;
}
return Page();
}
}
}
The first thing you need to know is that the pagination in the tutorial is the back-end pagination. When you click the next page, the data is re-requested every time, so if you want to submit in batches, you can only submit current page data.
If you want the data of the current page to be submitted in batches, then you can modify your code as follows.
PageModel:
public class IndexModel : PageModel
{
private readonly PageListRazorContext _context;
private readonly IConfiguration Configuration;
public IndexModel(PageListRazorContext context, IConfiguration configuration)
{
_context = context;
Configuration = configuration;
}
public string NameSort { get; set; }
public string KeywordsSort { get; set; }
public string CurrentSort { get; set; }
public PaginatedList<CompanyDataListing> CompanyDataListing { get;set; }
public async Task OnGetAsync(string sortOrder,int? pageIndex)
{
NameSort = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
KeywordsSort = sortOrder == "Keywords" ? "keywords_desc" : "Keywords";
IQueryable<CompanyDataListing> company = from s in _context.CompanyDataListing
select s;
switch (sortOrder)
{
case "name_desc":
company = company.OrderByDescending(s => s.CompanyName);
break;
case "Keywords":
company = company.OrderBy(s => s.Keywords);
break;
case "keywords_desc":
company = company.OrderByDescending(s => s.Keywords);
break;
default:
company = company.OrderBy(s => s.CompanyName);
break;
}
var pageSize = Configuration.GetValue("PageSize", 4);
CompanyDataListing = await PaginatedList<CompanyDataListing>.CreateAsync(
company.AsNoTracking(), pageIndex ?? 1, pageSize);
}
public IActionResult OnPost(List<CompanyDataListing> Datalist)
{
//....
return RedirectToPage("./Index");
}
}
Page:
<form method="post">
<table class="table">
<thead>
<tr>
<th>
<a asp-page="./Index" asp-route-sortOrder="#Model.NameSort">
#Html.DisplayNameFor(model => model.CompanyDataListing[0].CompanyName)
</a>
</th>
<th>
<a asp-page="./Index" asp-route-sortOrder="#Model.KeywordsSort">
#Html.DisplayNameFor(model => model.CompanyDataListing[0].Keywords)
</a>
</th>
<th>
#Html.DisplayNameFor(model => model.CompanyDataListing[0].GoogleCategory)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.CompanyDataListing)
{
<tr>
<td>
<input type="hidden" asp-for="#item.CompanyName" name="Datalist[#i].CompanyName" />
#Html.DisplayFor(modelItem => item.CompanyName)
</td>
<td>
<input type="hidden" asp-for="#item.Keywords" name="Datalist[#i].Keywords" />
#Html.DisplayFor(modelItem => item.Keywords)
</td>
<td>
<input asp-for="#item.GoogleCategory" name="Datalist[#i].GoogleCategory" placeholder="Input your keyword" class="form-control GoogleCategory" autofocus="autofocus" />
<span asp-validation-for="#item.GoogleCategory" class="text-danger"></span>
</td>
<td>
<a asp-page="./Edit" asp-route-id="#item.ID">Edit</a> |
<a asp-page="./Details" asp-route-id="#item.ID">Details</a> |
<a asp-page="./Delete" asp-route-id="#item.ID">Delete</a>
</td>
#{i++;}
</tr>
}
</tbody>
</table>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</div>
#{
var prevDisabled = !Model.CompanyDataListing.HasPreviousPage ? "disabled" : "";
var nextDisabled = !Model.CompanyDataListing.HasNextPage ? "disabled" : "";
}
<a asp-page="./Index"
asp-route-sortOrder="#Model.CurrentSort"
asp-route-pageIndex="#(Model.CompanyDataListing.PageIndex - 1)"
class="btn btn-primary #prevDisabled">
Previous
</a>
<a asp-page="./Index"
asp-route-sortOrder="#Model.CurrentSort"
asp-route-pageIndex="#(Model.CompanyDataListing.PageIndex + 1)"
class="btn btn-primary #nextDisabled">
Next
</a>
</form>
Test result:
You are referencing CustomerDisplayList in the OnPost handler but it has not been initialised, hence the exception. You initialised it in the OnGet handler, but that only executes for GET requests. If you want to use a POST request, you also need to initialise the CustomerDisplayList in that too.
For what it's worth, the example you linked to uses GET requests for the whole cycle. This usually makes more sense for things like paginating and filtering results. That way, the criteria are passed in the URL as query string values or route data, which means that you can bookmark filtered/paged results. You won't need to render the anti forgery token for GET requests.
I need to add an attribute display-name to <td> with values as wicket id.
<tbody>
<tr wicket:id="result" class="bgalternate1">
<td wicket:id="values">
<span wicket:id="value">Value</span>
</td>
</tr>
</tbody>
Expected result is
<tbody>
<tr class="bgalternate1">
<td display-name="<attribute_name>"> <!--attribute is column header -->
<span wicket:id="value">Value</span>
</td>
</tr>
</tbody>
I have tried using below java code, however unable to achieve the desired result, i.e unable to append the attribute "display-name" to <td>. I have initially used SimpleAttributeModifier as it is deprecated, used AttributeModifier.
public ReportResultPanel(final String id, final IModel<AdHocReportSetup> model)
{
super(id, model);
setOutputMarkupId(true);
final IModel<Paging> pagingModel = new Model<Paging>(new Paging());
resultModel = createResultModel(model, pagingModel);
addResults(this, "result", resultModel);
}
private ListView<AdHocReportResult> addResults(final MarkupContainer parent,
final String id,
final IModel<ReportResultModel> model)
{
final IModel<List<AdHocReportResult>> resultsModel = new PropertyModel<List<AdHocReportResult>>(model, "results");
final ListView<AdHocReportResult> result = new ListView<AdHocReportResult>(id, resultsModel) {
private static final long serialVersionUID = 1L;
#Override
protected void populateItem(final ListItem<AdHocReportResult> item)
{
addResultValues(item, "values", item.getModel());
AdHocPage.applyParityClass(item.getIndex(), item);
final Behavior behavior = AttributeModifier.append("display-name", "red");
for (final Component next : item)
{
next.add(behavior);
}
}
};
parent.add(result);
return result;
}
private ListView<AdHocReportResultAttribute> addResultValues(final
MarkupContainer parent, final String id,
final IModel<AdHocReportResult> model)
{
final IModel<List<AdHocReportResultAttribute>> attributesModel = new PropertyModel<List<AdHocReportResultAttribute>>(
model, "attributes");
final ListView<AdHocReportResultAttribute> result = new ListView<AdHocReportResultAttribute>(id, attributesModel) {
private static final long serialVersionUID = 1L;
#Override
protected void populateItem(final ListItem<AdHocReportResultAttribute> item)
{
addValueLabel(item, "value", item.getModel());
}
};
parent.add(result);
return result;
}
You are adding the AttributeModifier to the ListView but you really need to add it to its ListItems.
...
item.add(AttributeModifier.append("display-name", "red"));
addValueLabel(item, "value", item.getModel());
...
If I remove the div tag from the source code below my application runs with no error. But it displays an empty cell (which is correct). I just want to hide this if the cells are empty.
Thymeleaf html
<div th:object="${AppPortModel.Status}" th:if="${AppPortModel.Status} == 'CRITICAL'">
<h3>
MONITORING
</h3>
<table id ="apCritTable">
<thead>
<tr>
<th> Status </th>
<th> HostName </th>
<th> Port Name</th>
<th> Port Listening Count </th>
</tr>
</thead>
<tbody>
<tr th:each="AppPortModel, iterStat : ${showap}" th:if="${AppPortModel.Status == 'CRITICAL'}">
<td th:text ="${AppPortModel.Status}"></td>
<td th:text="${AppPortModel.host}">${AppPortModel.host}</td>
<td th:text="${AppPortModel.portOwner}"></td>
<td th:text="${AppPortModel.count}"></td>
</tr>
</tbody>
</table>
</div>
AppPortModel
public class AppPortModel implements Comparable {
private String Status;
private String host;
private String portName;
private String plCount;
//getters and setters
#Override int compareTo(Object o) {
return //stuff
}
Controller
#Controller
public class IndexController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView getdata() throws IOException {
ModelAndView model = new ModelAndView("index");
model.addObject("showap", apList);
return model;
}
AppPortList
#Component
public class AppPortList {
#Value("#{'$APP_SERVERS_PORT}'.split('#!')}")
private String[] apServerArray;
#Value("#{'${APP_SERVER_MONITORING_LIST}'.split('#!')}")
private String[] appServerPortsList;
#PostConstruct
public List<AppPortModel> getAppPortList() {
final int MYTHREADS = 80;
ExecutorService executor = Executors.newFixedThreadPool(MYTHREADS);
ApplicationPort.resetData();
try {
for (int z = 0; z < apServerArray.length; z++) {
String apServer = apServerArray[z];
String[] portListArray=appServerPortsList[z].split(",");
ApplicationPort apWorker = new ApplicationPort(apServer, portListArray);
executor.execute(apWorker);
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException in AppPortList");
}
finally {
executor.shutdown();
while (!executor.isTerminated()) {
}
logger.info("\nFinished all threads in App Port. ");
}
return ApplicationPort.getData();
}
Snippet of Class App
static List<AppPortModel> apData = new ArrayList<AppPortModel>();
public static List<AppPortModel> getData() {
return apData;
}
public static void setData(List<AppPortModel> apData) {
ApplicationPort.apData = apData;
}
public static void resetData(){
apData = new ArrayList<AppPortModel>();
}
public ApplicationPort(String apServer, String[] portListArray) {
this.apServer = apServer;
this.portListArray = portListArray;
}
This table will populate if AppPortModel.Status is CRITICAL. I am trying to hide this table if there is no values in this table. If I just have a regular div tag my code will run but I will have a awkward head and table row heads on my page with empty cells.
Attempt
I tried adding some th logic into my div tag, but I receive an null error.
<div th:object="${AppPortModel.Status}" th:if="${AppPortModel.Status == 'CRITICAL'}">
Attempt 2
<div th:if="${Status} == 'CRITICAL'">
This script would hide my div tag. Even if I have Status = to CRITICAL it would still hide the table.
You can check whether the list is empty using the following condition expression. Assuming the object showap is a List type,
<div th:if="${not #lists.isEmpty(showap)}">
--content--
</div>
Your h3 tag and table goes inside this div.
#lists is a thymeleaf utility class. Refer http://www.thymeleaf.org/apidocs/thymeleaf/2.0.2/org/thymeleaf/expression/Lists.html for more options. You can alternatively use size() method and check for list length.
i have this listView and textBox:
<table>
<tr><td>Reciver:<table><tr>
<asp:ListView ID="showRecivers" runat="server"><td><%# Eval("name")%></td> </asp:ListView>
</tr></table>
<asp:TextBox ID="reciver" runat="server" OnTextChanged="style_Recivers" AutoPostBack="true"></asp:TextBox>
</td></tr></table>
the list the listview is bound to:
public List<Reciver> recivers = new List<Reciver>();
and the function style_Recivers:
protected void style_Recivers(object sender, EventArgs e)
{
string[] separator = new string[] { "," };
string[] reciversArray = reciver.Text.ToString().Split(separator, StringSplitOptions.None);
reciversArray = reciversArray.Distinct().ToArray();
for (int i = 0; i < reciversArray.Length; i++)
{
recivers.Add(new Reciver(reciversArray[i]));
}
this.showRecivers.DataSource = recivers;
this.showRecivers.DataBind();
}
and class Reciver:
public class Reciver
{
public string name;
public Reciver(string name)
{
this.name = name;
}
public string getName()
{
return this.name;
}
public void setName(string name)
{
this.name = name;
}
}
what my idea is, that when a couple of names eneted to the textBox with a , saperator, the style_Reciver function is activated and each name is shown in the ListView right away.
but it doesnt work, it gives me the error
ASP.NET runtime error:code blocks are not supported in this context
and marks this line:
<asp:ListView ID="showRecivers" runat="server"><td><%# Eval("name")%></td> </asp:ListView>
for starter. probably more thing wont work but this is the first thing.
how can i fix it? Thanks for the help
EDIT:
it works after i added <ItemTemplate>
now it gives me a different bug:
Reciver' does not contain a property with the name 'name'
whhat is the problem now?
The List View content here should be wrapped into ItemTemplate:
<asp:ListView ID="showRecivers" runat="server">
<ItemTemplate>
<td><%# Eval("name")%></td>
</ItemTemplate>
</asp:ListView>
Update. Also there is a problem with your class declaration. Here is how it should be declared in C# conventional way:
public class Reciver
{
public string _name;
public Reciver(string name)
{
this.name = name;
}
public string name
{
get { return this._name; }
set { this._name = value; }
}
}
Does anyone know how to make nested server controls accept nested html without "injecting" it out from serverside, ie.
<uc1:CustomServerControl runat="server">
<NestedControl></NestedControl>
<NestedControl2></NestedControl2>
</uc1:CustomServerControl>
but to do this:
<uc1:CustomServerControl runat="server">
<div>
<NestedControl>
</NestedControl>
<NestedControl2></NestedControl2>
</div>
</uc1:CustomServerControl>
Try this:
Section.cs:
[ToolboxData("<{0}:Section runat=\"server\" />")]
public class Section : WebControl, INamingContainer
{
private SectionPartCollection _parts;
[Browsable(false), PersistenceMode(PersistenceMode.InnerProperty)]
public SectionPartCollection Parts
{
get
{
if (this._parts == null)
{
this._parts = new SectionPartCollection();
if (this.IsTrackingViewState)
((IStateManager)this._parts).TrackViewState();
}
return this._parts;
}
}
[Browsable(false), PersistenceMode(PersistenceMode.InnerProperty)]
public ITemplate LayoutTemplate { get; set; }
protected override void CreateChildControls()
{
base.CreateChildControls();
if (this.LayoutTemplate != null)
{
this.LayoutTemplate.InstantiateIn(this);
foreach (SectionPart part in this.Parts)
{
Control placeHolder = this.FindControl(part.PlaceHolderID);
if (placeHolder != null)
if (part.ContentTemplate != null)
part.ContentTemplate.InstantiateIn(placeHolder);
}
}
}
protected override void LoadViewState(object savedState)
{
object[] states = (object[])savedState;
base.LoadViewState(states[0]);
if (states[1] != null)
((IStateManager)this.Parts).LoadViewState(states[1]);
}
protected override object SaveViewState()
{
object[] states = new object[2];
states[0] = base.SaveViewState();
if (this._parts != null)
states[1] = ((IStateManager)this.Parts).SaveViewState();
return states;
}
protected override void TrackViewState()
{
base.TrackViewState();
if (this._parts != null)
((IStateManager)this._parts).TrackViewState();
}
}
SectionPart.cs:
[DefaultProperty("PartName")]
public class SectionPart : IStateManager
{
private StateBag _viewState;
private bool _isTrackingViewState;
[DefaultValue("")]
public string PlaceHolderID
{
get { return (string)this.ViewState["PlaceHolderID"] ?? string.Empty; }
set { this.ViewState["PlaceHolderID"] = value; }
}
[Browsable(false), PersistenceMode(PersistenceMode.InnerProperty)]
public ITemplate ContentTemplate { get; set; }
public void SetDirty()
{
if (this._viewState != null)
this.ViewState.SetDirty(true);
}
[Browsable(false)]
protected StateBag ViewState
{
get
{
if (this._viewState == null)
{
this._viewState = new StateBag(false);
if (this._isTrackingViewState)
((IStateManager)this._viewState).TrackViewState();
}
return this._viewState;
}
}
protected virtual bool IsTrackingViewState
{
get { return this._isTrackingViewState; }
}
protected virtual void LoadViewState(object state)
{
if (state != null)
((IStateManager)this.ViewState).LoadViewState(state);
}
protected virtual object SaveViewState()
{
if (this._viewState != null)
return ((IStateManager)this._viewState).SaveViewState();
return null;
}
protected virtual void TrackViewState()
{
this._isTrackingViewState = true;
if (this._viewState != null)
((IStateManager)this._viewState).TrackViewState();
}
bool IStateManager.IsTrackingViewState
{
get { return this.IsTrackingViewState; }
}
void IStateManager.LoadViewState(object state)
{
this.LoadViewState(state);
}
object IStateManager.SaveViewState()
{
return this.SaveViewState();
}
void IStateManager.TrackViewState()
{
this.TrackViewState();
}
}
SectionPartCollection.cs:
public class SectionPartCollection : StateManagedCollection
{
public SectionPart this[int index]
{
get { return (SectionPart)((IList)this)[index]; }
}
public void Add(SectionPart part)
{
if (part == null)
throw new ArgumentNullException("part");
((IList)this).Add(part);
}
public void Insert(int index, SectionPart part)
{
if (part == null)
throw new ArgumentNullException("part");
((IList)this).Insert(index, part);
}
public void Remove(SectionPart part)
{
if (part == null)
throw new ArgumentNullException("part");
((IList)this).Remove(part);
}
public void RemoveAt(int index)
{
((IList)this).RemoveAt(index);
}
protected override void SetDirtyObject(object o)
{
((SectionPart)o).SetDirty();
}
}
Example:
<uc:Section ID="Section1" runat="server">
<LayoutTemplate>
<table>
<tr>
<td id="TitlePlaceHolder" runat="server">
</td>
</tr>
<tr>
<td id="BodyPlaceHolder" runat="server">
</td>
</tr>
</table>
</LayoutTemplate>
<Parts>
<uc:SectionPart PlaceHolderID="TitlePlaceHolder">
<ContentTemplate>
<span>Title</span>
</ContentTemplate>
</uc:SectionPart>
<uc:SectionPart PlaceHolderID="BodyPlaceHolder">
<ContentTemplate>
<p>
Some content...</p>
</ContentTemplate>
</uc:SectionPart>
</Parts>
</uc:Section>
Try this:
[ToolboxData("..."), ParseChildren(false), PersistChildren(true)]
public class CustomServerControl : WebControl, INamingContainer
{
}
The purpose of this basicly is to have a custom Generic tag library, whick in this case will speak to a underlying object model. The objectmodel is responsible for splitting up articles into its respective parts, ie, Headline, blurb, Images, Comments etc. In this case I'm woring with a collection of them, and by specifying the inner tags, you basicly apply a filter onto what parts of the articles in the section you want to see.
<uc1:Section runat="server">
<HeadLine></HeadLine>
<Blurb></Blurb>
<Body></Body>
</uc1:Section>
Based on what the user specify by only tagging whatever he needs, the respective content will then be written to the frontend.
Now this works wonderfully well, except in one or two cases where you actually need some kind of internal structure to each of the individual parts of an article, and then projecting that onto the entire collection, like having a <table> where the headline should go into one <td> and the rest into another <td>
Hope it makes sense!!