marionette childViewContainer - Can it have two child containers - marionette

As per my requirement I need to show two different sets of data into two different child containers.
For Example:
ItemView
var itemView = new Marionette.ItemView.extend({
template : "<%=id%><%=name%>",
model : Model,
tagName: "tr"
});
CompositeView
Marionette.CompositeView.extend({
childView : itemView,
childViewContainer : "table.employee-table.new",
template : below html template
});
Html Template:
<div>
<table class="employee-table">
<thead>
<tr>
<th>id</th>
<th>Name</th>
</tr>
</thead>
<tbody class="new"></tbody>
<tbody class="old"></tbody>
</table>
</div>
I want to group old employees into the old (class="old") table body and new employees grouped into new (class="new") table body.

I have not tried doing it with 2 containers, but with 2 different views in the same collection, you can do it, by overriding getChildView function in Marionette.CompositeView
class Notifications extends Marionette.CompositeView
template: require './templates/player_notifications'
childView : Notification
childViewContainer : "#caption"
modelEvents:
"sync" : "render"
getChildView: (item) ->
if (item.get('type') == "notification:payment")
PaymentNotification
else if (item.get('type') == "notification:player:connected")
PlayerConnectedNotification
else if (item.get('type') == "notification:player:discovered")
PlayerDiscoveredNotification
else
Notification
class Notification extends Marionette.ItemView
template: require './templates/player_notification'
class PaymentNotification extends Marionette.ItemView
template: require './templates/payment_notification'
class PlayerConnectedNotification extends Marionette.ItemView
template: require './templates/player_connected'
class PlayerDiscoveredNotification extends Marionette.ItemView
template: require './templates/player_discovered'
In the same way there is a getChildViewContainer function in Marionette.CompositeView, which you can override.
Or just split your collection in 2 on fetch in your Backbone.Collection.

Related

Knockout.js code seems to be working intermittently

We use Knockout.js and MVC in a Webapp and are having an issue, where the order merchandise total observed is 0 by Knockout.js, as displayed in the GUI.
The code seems to be working intermittently, because sometimes we do show the merchandise total in other orders. All orders use the same code and a merchandise total non zero value is always seen in the
OrderDetailClientViewModel object within the controller before being passed to the view. The view is coded in Knockout.js and plain javascript.
The "Totals" property shown below is an object (Models.OrderTotalViewModel), which contains the "MerchandiseTotal" field, which is sometimes showing a 0. I'm showing the relevant parts of the two view files below. I don't see the merchandiseTotal value being modified erroneously in the code. Only helpful segments are shown below.
Any suggestions to fix this intermittent behavior would be greatly appreciated!!!
Thank you,
Ken
--Edit.cshtml
#model Models.OrderEditPageViewModel
...
var rawViewModel = #(Html.ToJson(Model.OrderDetailClientViewModel()));
var viewModel = ko.mapping.fromJS(rawViewModel,
{
'HeaderData': {
create: function(options) {
options.data.StartDate = new Date(options.data.StartDate);
options.data.EndDate = new Date(options.data.EndDate);
var headerData = ko.mapping.fromJS(options.data);
headerData.errors = new HeaderDataError();
return headerData;
}
},
'Totals': {
create: function(options) {
var totals = ko.mapping.fromJS(options.data);
totals.errors = new TotalsError();
totals.isPromoCodeApplied = ko.observable(false);
if ($.trim(totals.PromoCode()) !== "")
totals.isPromoCodeApplied(true);
return totals;
}
}
});
...
-- This segment in Edit.cshtml shows where the OrderTotalViewModel.cshtml is called for Totals.
<tr>
<td colspan="3">
#Html.EditorFor(m => m.Totals)
</td>
</tr>
--OrderTotalViewModel.cshtml
#model Models.OrderTotalViewModel
#{ Layout = null; }
...
<td colspan="3" style="text-align:right">
<table class="PaddedTable" style="width:925px">
<tbody>
<tr>
<td style="width:125px;text-align:right">Merchandise Total:</td>
<td style="text-align:right" class="NormalTextBold">
#(Html.Knockout().SpanFor(m => m.MerchandiseTotal)
.HtmlAttributes(new { #class = "NormalTextBold" })
.Currency())

How to add a menu generated from a doc type list in Umbraco?

I'm new to umbraco and i want to be able to click in a content field, add content, then select specialty nav item. This navigation would be queried from a custom doc type.
I have the doc type list setup and i have a generic custom grid editor setup, however im not sure how to get the grid editor render portion to actually query the doc type and output it.
I did this by using a macro and a partial template like so:
#inherits Umbraco.Web.Macros.PartialViewMacroPage
#{
var selection = CurrentPage.Site().FirstChild("benefitNav").Children("benefitNavItem").Where("Visible");
}
<div id="benefitmenu">
<table class="blink">
#foreach (var item in selection)
{
var img = Umbraco.Media(item.GetPropertyValue("benefitIcon")).Url;
foreach (var link in #item.linkToPage)
{
<tr>
<td class="bicon"><img alt="#link.caption" src="#img" /></td>
<td class="btext">#link.caption</td>
</tr>
}
}
</table></div>

Pagination and sorting in Spring MVC 4

I'm building a web app using spring mvc 4, thymeleaf and mysql (jdbc is used not hibernate or JPA) .. and I'm trying to do pagination and sorting, but I think I have a problem understanding it.
When I search for pagination using spring mvc all I can find is PagedListHolder and MutableSortDefinition, but I don't think it's the right way to go since it will load a list of all the data in server memory for each request, is that right? and if so, then what is the best way to implement pagination and sorting given that there are hundreds of thousands of records (advertisements for real-estate over a month, with almost 2500 ads a day)
So, could someone put a real-world example of how to implement pagination and sorting in a way that can be used with large data apps?
Try this way :
findAll method with argument "PageRequest()" provides the server side pagination
there are two methods
PageRequest(int page, int size)
PageRequest(int page, int size, Direction direction, String... properties)
View :
<table class="table">
<thead style="background-color: #eee">
<tr>
<td>Dispature</td>
<td>Service</td>
<td>Host</td>
<td>Value</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in app.metricsList">
<td>{{x.dispature}}</td>
<td>{{x.service}}</td>
<td>{{x.host}}</td>
<td>{{x.value}}</td>
</tr>
</tbody>
</table>
<div align="center">
<uib-pagination items-per-page="app.itemPerPage" num-pages="numPages"
total-items="app.totalItems" boundary-link-numbers="true"
ng-model="app.currentPage" rotate="false" max-size="app.maxSize"
class="pagination-sm" boundary-links="true"
ng-click="app.getPagableRecords()"></uib-pagination>
<div style="float: right; margin: 15px">
<pre>Page: {{app.currentPage}} / {{numPages}}</pre>
</div>
</div>
Js Controller :
app.controller('AllEntryCtrl',['$scope','$http','$timeout','$rootScope', function($scope,$http,$timeout,$rootScope){
var app = this;
app.currentPage = 1;
app.maxSize = 5;
app.itemPerPage = 5;
app.totalItems = 0;
app.countRecords = function() {
$http.get("countRecord")
.success(function(data,status,headers,config){
app.totalItems = data;
})
.error(function(data,status,header,config){
console.log(data);
});
};
app.getPagableRecords = function() {
var param = {
page : app.currentPage,
size : app.itemPerPage
};
$http.get("allRecordPagination",{params : param})
.success(function(data,status,headers,config){
app.metricsList = data.content;
})
.error(function(data,status,header,config){
console.log(data);
});
};
app.countRecords();
app.getPagableRecords();
}]);
Controller :
#RestController
public class HomeController {
#Autowired
private HomeRepo repo;
#RequestMapping(value = "allRecordPagination", method = RequestMethod.GET)
public Page<Metrics> getAllRecordPagination(#RequestParam("page") int page, #RequestParam("size") int size){
return repo.findAll(new PageRequest(page-1, size));
}
}
Repository :
#Repository
public interface HomeRepo extends JpaRepository<Table, String>{
}
In order to expand my comments I want to share some code snippets to show how easy it is to implement Dandelion Datatables with Thymeleaf.
So, on the client side I have two files: html for table render
....
<table id="dTable" class="display dataTable" dt:table="true">
<thead>
<tr>
<th th:text="#{requestId}"></th>
<th th:text="#{clientTime}"></th>
<th th:text="#{requestDate}"></th>
<th th:text="#{receiver}"></th>
</tr>
</thead>
</table>
....
and js for table initialization
$(document).ready(function() {
$('#dTable').DataTable( {
ajax: { url: "/bhost/dtable_list"},
processing: true,
serverSide: true,
bFilter: false,
columns: [
{ data: "requestId" },
{ data: "clientTime" },
{ data: "requestDate" },
{ data: "receiver", orderable: false },
],
lengthMenu: [50, 100, 200, 500],
language: {
thousands: " "
}
} );
} );
Even though it's possible to configure dandelion datatables only in html I prefer to use JQuery way to do it, since it's more flexible.
On the server side we used our own created database access layer (not quite useful to share it) and dandelion DatatablesCriterias class to get current state of table (current page index, page length, selected sorted column etc.)
Controller
....
#RequestMapping(value = "/dtable_list")
#ResponseBody
public DatatablesResponse<DataDTO> getTableData(HttpServletRequest request) {
HttpSession session = request.getSession();
DataModel model = (DaatModel) session.getAttribute(MODEL_NAME);
DatatablesCriterias criterias = DatatablesCriterias.getFromRequest(request);
List<DataDTO> list = finder.getForCriterias(model, timeZoneOffset, criterias);
Long totalCount = model.getCount();
return DatatablesResponse.build(new DataSet<>(list, totalCount, totalCount), criterias);
}
....
The key feature here is DatatablesCriterias, since it contains all necessary data to retrieve entries that correlate with user selection.
And that's pretty much it (Except configuration part, I guess)
this is an example of pagination with SpringBoot and Thymeleaf templates, try it!!
clone it and run it

Print a value which is later known in the view in Razor

Is there in Razor a way to print some HTML on the page
while the value later known in the view?
For example: I would like to print the sum of an expensive calculation, and that sum should be before the items in the HTML. But with the example below, it will always print 0.
I would like to calculate the sum only once.
I would like to solve this in the view, not in a csharp helper or on the client side (css, javascript etc)
#{
var sum = 0;
}
<table>
#* I would like to print here the sum which is known after the foreach loop*#
<tr><td>total: #sum</td></tr>
#foreach (var item in items)
{
<tr>
#{
var x= item.expensiveCalculation();
sum+= x;
}
//print item with x
<td>#x</td>
</tr>
}
</table>
edit: It is very important that the expensiveCalculation() is only calculated once for each item!
Your model is not adapted to the requirements of the view. Full stop.
So when your model is not adapted to the requirements of your view you go ahead and define a view model so that all the expensive operations are done inside the controller.
So:
public class ItemViewModel
{
public decimal Price { get; set; }
public string Name { get; set; }
}
Now your view becomes strongly typed to the view model and there are no longer expensive operations there:
#model IEnumerable<ItemViewModel>
<table>
<tr>
<td>
total: #Model.Sum(item => item.Price)
</td>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#item.Name - #item.Price<td>
</tr>
}
</table>
and now inside your controller action prepare this view model and pass it to the view:
public class SomeAction()
{
IEnumerable<Item> items = ... go and fetch your domain models from wherever you are fetching them
// now let's build the view model
var model = new MyViewModel
{
Items = items.Select(x => new ItemViewModel
{
Name = x.Name,
Price = x.expensiveCalculation()
})
};
// and we are obviously passing the view model to the view, not the domain model
return View(model);
}
As you can see we are doing the expensive operations for each element inside the controller in order to bind it to the corresponding property of the view model (Price) but we are no longer paying this expensive operations price inside the view as we are simply summing over the view model pre-calculated properties.
And next time when you encounter a problem in ASP.NET MVC don't forget that view models are the solution to your problem.

How to open cshtml file in new tab from controller's method?

I'm working on a Nopcommerce, and need to generate Invoice (custom made not as what they already provide, because it just doesn't solve our purpose). We need to generate Invoice
in new tab(using another cshtml file) using Controller's method also I'm passing model data on view.
<tr>
<td class="adminTitle">
#Html.NopLabelFor(model => model.ProbableDeliveryDate):
</td>
<td class="adminData">
#Html.EditorFor(model=>model.ProbableDeliveryDate)
</td>
</tr>
<tr>
<td>
#if(Model.CanGenrateInvoice)
{
<input type="submit" name="generateinvoice" value="#T("Admin.Orders.Fields.generateinvoice")" id="generateinvoice" class="adminButton" />
}
</td>
</tr>
I've to post data to get value of probableDeliveryDate to controller method and after that want to open view in new tab.
How can i do this?
If you are getting to the action from the first page via an Html.ActionLink you can do this:
Html.ActionLink("Open Invoice", "ActionName","ControllerName", new { id = Model.InvoiceID }, new { target = "_blank" });
Specifying target = "_blank" will open in the new tab
Update
Since you are posting the model to the controller (I was hoping RedirectToAction could help open a new window/tab but that doesn't look to be the case)
My spidy sense is tingling on the flow you have tho... This is just me but I would do something a little different.. such as
Post the model to the controller
Save the data that generates the invoice
Return the InvoiceID to the action
Add the InvoiceID to the model
Send the model back to the view
Inform the user that
the invoice was generated and show a link - like above - that allows the user to open the invoice OR
this provides the perfect clean solution to show model errors if there were any
Your view could have a piece of razor code that did that:
#{
if(Model.InvoiceID != null && Model.InvoiceID !=0) {
#Html.ActionLink("Open Invoice", "ActionName","ControllerName", new { id = Model.InvoiceID }, new { target = "_blank" });
}
}

Resources