Blazor, how can I change a component in MainLayout when I change page - components

I want to add a toolbar inside website, the toolbar change inside component on each page. For now, I have this but I want my toolbar to be like this. How could i make this toolbar to update depend on the page the user go ?
The toolbar would be in the MainLayout and need to change content with a switch (not the best option I think) or is it possible to give new content to MainLayout from the page content ?
This is the code for the banner component :
<div class="extend-space" style="left:#($"-{Convert.ToInt32(offsetX)}px")">
<div class="banner" style="left:#(Convert.ToInt32(offsetX)+"px");width:#(Convert.ToInt32(width)+"px");">
<div class="banner-title">
#if (Icon != null)
{<i id="banner-title-icon" class="icon fas fa-#Icon"></i>}
<h3 class="title">#Title</h3>
</div>
<div class="toolbar">
<span id="arrow-left" class="scrollable" onclick="lastTool()">
<i class="fas fa-angle-left arrow"></i>
</span>
<span id="toolbar">
#ChildContent
</span>
<span id="arrow-right" class="scrollable" onclick="nextTool()">
<i class="fas fa-angle-right arrow"></i>
</span>
</div>
</div>
ChildContent should be a list of buttons with function onclick on it so this is the part that need to update on each page.
I add an example of how I use it on a page :
<XLBanner Title="Catégories" Icon="sitemap">
<XLButton Icon="plus" Content="#SharedLocalizer["Add"]" OnClickFunction="#AddCategorie" />
<XLButton Icon="save" Content="#SharedLocalizer["Save"]" OnClickFunction="#Save" disabled="#(!UnsavedChanges)" />
<XLButton Icon="redo" Content="#SharedLocalizer["Reset"]" OnClickFunction="#DeleteUnsavedChanges" disabled="#(SelectedCategorie == null)" />
<XLButton Icon="trash-alt" Content="#SharedLocalizer["Remove"]" OnClickFunction="#SuppCategorie" disabled="#(SelectedCategorie == null)" />
<XLButton Icon="copy" Content="#SharedLocalizer["Copy"]" OnClickFunction="#CopyCategorie" disabled="#(SelectedCategorie == null)" />
<XLButton Icon="download" Content="#SharedLocalizer["Export"]" OnClickFunction="#Export" /
</XLBanner>
What would be needed to update is the XLButton and the OnClickFunction.
My banner has differents tools depend on the page exemple dashboard page, exemple categorie page

If I understand the question correctly a version of this should work for you.
Basically:
Create a simple service that holds the menu data and has an event that is raised whenever the menu data changes and register it.
Use a DynamicComponent in Layout that plugs into the service.
Trigger StateHasChanged on the Layout whenever the service raises a menu change event.
Set the menu you want in each page in OnInitialized.
Two "Menus" to work with:
Menu1.razor
<h3>Menu1</h3>
Menu2.razor
<h3>Menu2</h3>
A simple LayoutService
public class LayoutService
{
public Type MenuControl { get; private set; } = typeof(Menu1);
public Dictionary<string, object>? MenuParameters { get; private set; }
public event EventHandler? MenuChanged;
public void ChangeMenu(Type menu)
{
this.MenuControl = menu;
MenuChanged?.Invoke(this, EventArgs.Empty);
}
public void ChangeMenu(Type menu, Dictionary<string, object> parameters)
{
this.MenuParameters = parameters;
this.MenuControl = menu;
MenuChanged?.Invoke(this, EventArgs.Empty);
}
}
registered in Program.cs:
builder.Services.AddScoped<LayoutService>();
MainLayout.razor
#inherits LayoutComponentBase
#inject LayoutService LayoutService;
#implements IDisposable
<PageTitle>BlazorApp1</PageTitle>
<DynamicComponent Type=this.LayoutService.MenuControl Parameters=this.LayoutService.MenuParameters />
<div class="page">
<div class="sidebar">
<NavMenu />
</div>
<main>
<div class="top-row px-4">
About
</div>
<article class="content px-4">
#Body
</article>
</main>
</div>
#code {
protected override void OnInitialized()
=> this.LayoutService.MenuChanged += this.MenuChanged;
private void MenuChanged(object? sender, EventArgs e)
=> this.InvokeAsync(StateHasChanged);
public void Dispose()
=> this.LayoutService.MenuChanged -= this.MenuChanged;
}
And example page:
#page "/"
#inject LayoutService LayoutService
Page Content
#code {
protected override void OnInitialized()
{
this.LayoutService.ChangeMenu(typeof(Menu1));
}

Don't get too focused on the layout as a single entity that you have to use for every page in the whole site. You can have as many Layout components as you want, and you can nest them just like you would with any class and derived class.
https://blazor-university.com/layouts/nested-layouts/

Related

Posting an array of string

I am trying to post a string array to the post action in an Razor Pages project. For this, I thought about using a hidden <select> tag. The user would enter text into a text box, press a button and I would then add a new option to the <select> then post the whole thing with a submit button. However, after everything is posted, the array property of my model is empty.
Does anyone know if there is a better way of doing this or what I am doing wrong?
Razor:
<form method="post">
<input id="string-value" />
<input type="button" id="add-item" value="Add item" />
<select asp-items="#Model.Model.ArrayOfStrings" id="hidden-select"></select>
<table id="table-items">
</table>
<input type="submit" value="Submit" />
</form>
public class ArrayModel
{
public List<SelectListItem> ArrayOfStrings { get; set; } = new List<SelectListItem>();
}
public class IndexModel : PageModel
{
[BindProperty]
public ArrayModel Model { get; set; }
public void OnGet()
{
Model = new ArrayModel();
}
public void OnPost()
{
System.Diagnostics.Debugger.Break();
}
}
JS:
$('#add-item').on('click', function () {
debugger;
var value = $('#string-value').val();
$('#hidden-select').append(new Option(value, value));
$('#table-item tr:last').after('<tr><td>' + value + '</td></tr>')
});
Repository can be found here.
The options of the select will not be posted so this will not work.
The easiest way to do this is append the results to a hidden input with a separator char, then do a string split on the server side.
Another, maybee more elegant way, would be to add hidden inputs with the same name. Each input with it's own value. You should then be able to get this as a List or Array on the server.
Razor:
<input value="#String.Join(",", Model.Model.ArrayOfStrings)" id="tags"></select>
JS
$('#tags').val($('#tags').val() + ',' + value);
Controller
public void OnPost(string tags)
{
var tagsArray = tags.split(',');
}

Handle onfocus event in Razor Pages

I have rows of <textarea />s and want to handle the onfocus and onblur events and pass along the row data. Cannot get it to work at all.
<div>
#foreach (Person p in People){
<textarea rows="4" onfocus="#hasFocus(p)" onblur="#lostFocus(p)">p.Name</textarea>
}
</div>
public void hasFocus(Person p) {
...
}
The events are not triggering.
This works for me:
<div>
#foreach (Person p in People){
<textarea rows="4"
#onfocus="#( () => hasFocus(p) )"
#onblur="#( () => lostFocus(p) )">
p.Name
</textarea>
}
</div>
According to docs, the event attribute name is #on{eventname}.
Then use a lambda to pass your person parameter.
Use #onfocus and #onblur
<textarea rows="4" #onfocus="hasFocus" #onblur="lostFocus">p.Name</textarea>
and
public void hasFocus(FocusEventArgs args)
{
}
public void lostFocus(FocusEventArgs args)
{
}
If you use only onfocus it will be an html attribute and not an eventlistener.
To pass your person object you need an action like this
#onfocus="(args) => hasFocus(p)"

Want to make navigation dynamic in MainLayout (Blazor.net)

Fail to make navigation in Blazor.net (Core 3.0 alpha 6) dynmic (loaded by Http Get Method)
I tried to include in "MainLayout.razor" file of default blazor project template the following dynamic loop.
the #body content was loaded correctly but navigation menu remains empty...
#inherits LayoutComponentBase
#using Pegasus.Shared
#inject HttpClient Http
<div class="sidebar">
#if (categories == null)
{
<p><em>Loading...</em></p>
}
else
{
#foreach (var category in categories)
{
<div>#category.Name</div>
}
}
</div>
<div class="main">
<div class="top-row px-4">
About
</div>
<div class="content px-4">
#Body
</div>
</div>
#code{
gb_Category[] categories;
protected override async Task OnInitAsync()
{
Console.WriteLine("Test");
var storeId = new Guid("c72d9757-98d5-4da2-89ea-2ffe44490162");
categories = await Http.GetJsonAsync<gb_Category[]>($"api/Category/actives/{storeId}");
}
}
No error message but empty navigation menu and I don't know why exaclty right now...
Same code runs if I put it into #page "/" but within #body of the MainLayout...
Goal is to load navigation items dynamic via Http and afterwards navigate through main data (#page's).
Thx

Panel created dynamically is shown on XHTML but missing on getViewRoot

Panel is created and added to xhtml right but when I get it using findComponent("-formBotones-wizardEventContainer").getChildren() the result is null because its container got 1 children (id=tempTextIdLayer) when really html source show several children.
I've tried a solution with visitTree() but vars target and panel are the same, wizarEventContainer, and the got only 1 children (input hidden)
HtmlPanelGroup panel=(HtmlPanelGroup)FacesContextWrapper.getCurrentInstance().getViewRoot().findComponent("formBotones-wizardEventContainer");
panel.visitTree(VisitContext.createVisitContext(FacesContext.getCurrentInstance()),new VisitCallback() {
#Override
public VisitResult visit(VisitContext context, UIComponent target) {
if (target instanceof HtmlPanelGroup) {
HtmlPanelGroup layer = (HtmlPanelGroup) target;
System.out.println("id: " + layer.getId()); //wizardEventContainer // Collect them in an arraylist orso.
}
return VisitResult.ACCEPT;
}
});
Main xhtml code
<h:form id="formBotones" prependId="true">
<h:panelGroup layout="block" id="wizardEventContainer" styleClass="wizardEventContainer">
<h:inputHidden id="tempTextIdLayer" value="#{eventProvider.tempTextIdLayer}" />
</h:panelGroup>
</h:form>
HTML when panel is added
<form id="formBotones">
<input type="hidden" value="formBotones" name="formBotones">
<div class="wizardEventContainer" id="formBotones-wizardEventContainer">
<div data-widget="widget_formBotones_text_11_0" id="formBotones-text_11_0">
<div class="ui-panel-content ui-widget-content" id="formBotones-text_11_0_content">
<span id="formBotones-editor_text_11_0">Dynamic text</span>
</div>
<div class="ui-resizable-handle ui-resizable-e" style="z-index: 90;"></div>
<div class="ui-resizable-handle ui-resizable-s" style="z-index: 90;"></div>
<div class="ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se" style="z-index: 90;"></div>
</div>
<input type="hidden" value="text_11_0" name="formBotones-tempTextIdLayer" id="formBotones-tempTextIdLayer">
</div>
<input type="hidden" value="e5s4" id="javax.faces.ViewState" name="javax.faces.ViewState">
</form>
Create layers code
Here, it's a method which is setted to button's actionListener. It create a resizable and draggable panel with a span where I'll write dynamic text through javaScript.
public void createTextLayer() throws IOException{
logger.entry("EventProvider.createTextLayer()");
Application app=FacesContextWrapper.getCurrentInstance().getApplication();
UIComponent parent=FacesContextWrapper.getCurrentInstance().getViewRoot().findComponent("formBotones-wizardEventContainer");
CommandButton textBtn=(CommandButton)FacesContextWrapper.getCurrentInstance().getViewRoot().findComponent("formControl-textLayerBtn");
String finalId=null;
if(tempObjs!=null && tempObjs.size()>0 && tempObjs.containsValue("text")){
finalId="text_" + space.getIdSpace() + "_" + createFinalIndex("text");
}
else{
finalId="text_" + space.getIdSpace() + "_" + spaceBo.getDao().countSectionPages(space.getIdSpace(),4);
}
if(parent!=null){
HtmlPanelGroup panel=(HtmlPanelGroup)app.createComponent(HtmlPanelGroup.COMPONENT_TYPE);
panel.setId(finalId);
panel.setStyleClass(panel.getId());
panel.setStyle("display:inline-block;min-width:100px;min-height:100px;background:red;overflow:hidden;");
setTempTextIdLayer(finalId);
HtmlOutputText text=(HtmlOutputText) app.createComponent(HtmlOutputText.COMPONENT_TYPE);
text.setId("editor_" + panel.getId());
panel.getChildren().add(text);
Resizable resizable=(Resizable)app.createComponent(Resizable.COMPONENT_TYPE);
resizable.setFor(panel.getId());
resizable.setMaxWidth(new Integer(800));
resizable.setMaxHeight(new Integer(600));
resizable.setMinWidth(new Integer(50));
resizable.setMinHeight(new Integer(50));
resizable.setContainment(false);
resizable.setFor(panel.getId());
panel.getChildren().add(resizable);
Draggable drag=(Draggable)app.createComponent(Draggable.COMPONENT_TYPE);
drag.setFor(panel.getId());
drag.setOpacity(new Double(0.6));
drag.setContainment(new String("parent"));
drag.setSnap(true);
drag.setSnapMode(new String("outer"));
drag.setSnapTolerance(new Integer(5));
drag.setFor(panel.getId());
panel.getChildren().add(drag);
tempObjs.put(panel,"text");
}
updateViewRoot();
//Disabling text button
textBtn.setDisabled(true);
}
Add layer to container code
Here I get the container, wizardEventContainer, and I add every panel which are saved on tempObjs var.
public void updateViewRoot(){
logger.entry("EventProvider.updateViewRoot()");
UIComponent parent=FacesContextWrapper.getCurrentInstance().getViewRoot().findComponent("formBotones-wizardEventContainer");
if(parent!=null){
for (Entry<UIComponent, String> entry : tempObjs.entrySet()) {
parent.getChildren().add(entry.getKey());
}
}
}
As getViewRoot() only return elements which are written on xhtml file I've decided to save dynamic components in a map and when I place this dragabble component in the right site the I pass css style and other properties through managed bean properties, so every time a new panel is added on xhtml I create a new dynamic component with new properties setted and I replace for old dynamic component saved in the map.
It's a no elegant way but works fine at the moment for me.
public void saveTextLayer(){
logger.entry("EventProvider.saveTextLayer()");
List<UIComponent> list=null;
if(tempObjs.containsValue("text"))
list=getKeysByValue(tempObjs,"text");
for (UIComponent c:list){
if (c instanceof HtmlPanelGroup){
HtmlPanelGroup panel=(HtmlPanelGroup)c;
if(panel.getId().equals(getTempTextIdLayer())){
panel.setStyle(getTempCSS());
if(panel.getChildren().get(0) instanceof HtmlOutputText){
((HtmlOutputText)panel.getChildren().get(0)).setValue(getTempHTML());
}
//Adding delete layer
Application app=FacesContextWrapper.getCurrentInstance().getApplication();
HtmlPanelGroup deleteLayer=(HtmlPanelGroup)app.createComponent(HtmlPanelGroup.COMPONENT_TYPE);
deleteLayer.setId("delete_" + panel.getId());
deleteLayer.setStyle("display:inline-block;width:5px;height:5px;background:white;");
deleteLayer.setOnclick("deleteLayer($(this));");
panel.getChildren().add(0,deleteLayer);
//Replacing UIComponent
tempObjs.remove(c);
tempObjs.put(panel, "text");
updateViewRoot();
//Deleting temp vars
setTempCSS("");
setTempTextIdLayer("");
setTempHTML("");
}
}
}

Model object passed to HttpPost action is having null values

I have a model with properties declared, Controller actions. and View with Viewmodel specified. I fill data in the form and submit, but model has only null values for all properties. If i try with view model i get same null values in HttpPost action.
My Model:
public class Supplier
{
public string SupplierSequenceNumber { get; set; }
public string SupplierName { get; set; }
public string SupplierActive { get; set; }
}
My Controller:
[HttpGet]
public ActionResult Add()
{
SupplierVM objSupplierVM = new SupplierVM();
return View(objSupplierVM);
}
[HttpPost]
public ActionResult Add(Supplier objSupplier)
{
return View();
}
My View:
#model AIEComm.ViewModel.SupplierVM
#using (Html.BeginForm("Add", "Supplier", FormMethod.Post, new { id = "formAddSupplier" }))
{
<div class="control-group">
#Html.LabelFor(m=>m.objSupplier.SupplierName, new{#class = "control-label"})
<div class="controls">
#Html.TextBoxFor(m => m.objSupplier.SupplierName, new { placeholder = "Swatch Style" })
#Html.ValidationMessageFor(m=>m.objSupplier.SupplierName)
</div>
</div>
<div class="control-group">
#Html.LabelFor(m=>m.objSupplier.SupplierActive, new{#class = "control-label"})
<div class="controls">
#Html.DropDownListFor(m=>m.objSupplier.SupplierActive,new SelectList(AIEComm.Models.Utilities.YesNoSelectList,"Value","Text"),new{#class=""})
#Html.ValidationMessageFor(m=>m.objSupplier.SupplierName)
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn btn-primary" id="btnSubmit" value="Add"/>
</div>
</div>
}
The reason for this is the following code:
m => m.objSupplier.SupplierName
You're generating HTML elements with a model that is inside a ViewModel. This is a good approach, and your problem can be solved quite easily.
It's a good approach because you're keeping things organised, but it's not working because the above code is saying:
Ok, using the ViewModel object (m), take the objSupplier object and then use the SupplierName property.
This is fine, but then when you're submitting data, you're saying (to the action):
Hi, I have a SupplierName property. Please put this into the objSupplier object which you can find inside the ViewModel object.
To which the action says "Well, I am expecting an objSupplier object, but what's this ViewModel you speak of?"
A simple solution is to create a new partial view to generate your form. It's model type should be:
_SupplierForm.cshtml
#model Supplier
#* // The Form *#
In your View, continue to use the same ViewModel, but pass in the correct supplier model:
#model AIEComm.ViewModel.SupplierVM
#Html.Partial("_SupplierForm", Model.objSupplier)

Resources