Blazor RenderFragment to String - c#

I'm developing a code block component using .Net 6 Blazor wasm. I need to display the RenderFragment as string and also render the component in my html.
Here is my code block component,
<pre class="language-html">
<code class="language-html">
#("Some way to get non rendered html from #ChildContent")
</code>
</pre>
#ChildContent
#code
{
[Parameter]
public RenderFragment ChildContent { get; set; }
}
I'm using the above component as,
<CodeBlock>
<Chat></Chat>
</CodeBlock>
Expected Output:
<Chat></Chat>
<!-- This is the input I passed inside as RenderFragment and I need the exact Render Fragement Code;
not the Rendered Html code of the RenderFragment -->
Component gets rendered as expected. But unable to get non rendered html of my RenderFragment
One option is to pass the RenderFragment content as string parameter to CodeBlock component. But this results in duplicate and non readable HTML. Also this becomes difficult to maintain when the ChildContent has multiple lines of code.
<CodeBlock Html="#("<Chat></Chat>")">
<Chat></Chat>
</CodeBlock>
Any hints/suggestions on how to achieve this?

This is kind of a tough question. From what I understand you want to be able to render the ChildContent of your component but also be able to view the ChildContent data as plaintext razor code, or HTML if that's what's in your ChildContent, right?
So an option would be to surround your #ChildContent renderer tag with a <div> and assign that div a unique id when the parent component is initialized. Then you create another variable, let's call it private string RawContent { get; set; }. Then write a javascript function that takes an id value and gets the element by id from the DOM and returns the element's innerHTML.
I created a test project to try it and it works. Here are the snippets that are relevant.
In your Component.razor file:
#inject IJSRuntime JS
<pre class="language-html">
<code class="language-html">
#RawContent
</code>
</pre>
<div id="#ElementId">
#ChildContent
</div>
#code
{
[Parameter]
public RenderFragment ChildContent { get; set; }
private ElementReference DivItem { get; set; }
private string RawContent { get; set; }
private Guid ElementId { get; set; } = Guid.NewGuid();
protected async override Task OnInitializedAsync()
{
base.OnInitializedAsync();
RawContent = await JS.InvokeAsync<string>("GetElementHtmlText", ElementId.ToString());
}
}
Then in your index.html file add this in side of a <script> tag, or to one of your javascript files:
async function GetElementHtmlText(elementID) {
await setTimeout(() => { }, 1);
console.log(elementID);
var element = document.getElementById(elementID);
console.log(element);
var result = element.innerHTML;
console.log(result);
return result;
}
Then anywhere you wish to use this component you will render the HTML markup and have the Raw Text available as well. However this function will return all of the html markup raw text, meaning that you get the razor tags and the empty comment elements that Blazor inserts as well (ie. <!--!-->). But as long as you know that you can work around them.
I didn't do this but you could modify this to call the JSInterop function inside the RawContent's getter instead of just when the component initializes.

Related

Passing reference of component to its ChildContent components

To add some context, I'm trying to create a Dropdown select Blazor component. I've managed to create a concept of this entirely with CSS, #onclick, and #onfocusout.
I'm trying to pass a reference of the DropDown component to its children, DropDownItem. The only way I know how to achieve this, is by using the #ref and passing it as a parameter to the DropDownItem component.
<DropDown #ref="DropDownReference">
<DropDownItem ParentDropDown=#DropDownReference>Hello</DropDownItem>
<DropDownItem ParentDropDown=#DropDownReference>World</DropDownItem>
</DropDown>
There has to be a cleaner approach here that does not require manually passing the reference down to each child instance. I suppose I could use CascadingValue but that will still require me to store the DropDown reference.
I'm trying to notify DropDown parent when a click event occurs in DropDownItem. This will signal the parent to changes it selected value - as it would traditionally work in a select.
Here is an example of how you could do it using CascadingValue. The DropDownItem component will accept a [CascadingParameter] of type DropDown. There is nothing wrong in doing that, this is how it's done in most (if not all) component libraries.
DropDown.razor
<CascadingValue Value="this" IsFixed="true">
#* Dropdown code *#
<div class="dropdown">
#ChildContent
</div>
</CascadingValue>
#code {
[Parameter] public RenderFragment ChildContent { get; set; }
private string selectedItem;
public void SelectItem(string item)
{
selectedItem = item;
StateHasChanged();
}
}
DropDownItem.razor
#* Dropdown item code *#
<div class="dropdown-item" #onclick="OnItemClick">...</div>
#code {
[CascadingParameter] public DropDown ParentDropDown { get; set; }
[Parameter] public string Name { get; set; }
private void OnItemClick()
{
ParentDropDown.SelectItem(Name);
}
}
Usage:
<DropDown>
<DropDownItem Name="Hello">Hello</DropDownItem>
<DropDownItem Name="World">World</DropDownItem>
</DropDown>

Blazor Closes the div tag on a conditionally div wrapper

Im trying to wrap one of my components on some specific tag based on some conditions.
To make it simple lets say that i have a
<div class="inner-class">
this must be in inner-class div and wrapped in some-class div
</div>
And if 'condition' == true then it should wrap it in another div the result should be like this
<div class="wrapper-class">
<div class="inner-class">
this must be in inner-class div and wrapped in some-class div
</div>
</div>
And before you say, use if-else method. i must say no. because the tag and the class in it is dynamic so i cant write it like that.
What i tried to do is
#if (condition)
{
#:<div class="wrapper-class">
}
<div class="inner-class">
this must be in inner-class div and wrapped in some-class div
</div>
}
#if (condition)
{
#:</div>
}
I Thought it should do the job.
But the problem is the browser closes the outer div before putting the inner div in it.
You have to use BuildRenderTree
With BuilderRenderTree you have full control to build component html.
For more information read this good article Building Components Manually via RenderTreeBuilder
I ended up writing a wrapper component similar to this to solve this problem pretty elegantly:
#if (Wrap)
{
<div id="#Id" class="#Class">
#ChildContent
</div>
}
else
{
#ChildContent
}
#code
{
[Parameter] public string? Id { get; set; }
[Parameter] public string? Class { get; set; }
[Parameter] public RenderFragment? ChildContent { get; set; }
[Parameter] public bool Wrap { get; set; }
}
It doesn't support dynamic tag types, but that would be pretty easy to create using a component implementing BuildRenderTree as mRizvandi suggested.
If it's a simple layout like you've described than you can make use of the MarkupString. The trick is understanding that MarkupString will automatically close any tags that are left open. Therefore you just need to build the entire string properly before trying to render it as a MarkupString.
#{ bool condition = true; }
#{ string conditionalMarkup = string.Empty; }
#if (condition)
{
conditionalMarkup = "<div class=\"wrapper-class\">";
}
#{ conditionalMarkup += "<div class=\"inner-class\"> this must be in inner-class div and wrapped in some-class div </div>"; }
#if (condition)
{
conditionalMarkup += "</div>";
#((MarkupString)conditionalMarkup)
}
else
{
#((MarkupString)conditionalMarkup)
}
I do this for building simple conditional markup. Usually inside of an object iteration making use of String.Format to fill in property values.

Convert static html page to Blazor Page

I have build a static website, a long time ago, with Nicepage.
But i want to convert this project into a Blazor project, so i can use some C# code.
To achieve this, i copy/paste the code of a html page, into a razor file, except the script tags (i put them into index.html).
The issue is that elements are not well render.
For example, i have an image that i want to be visible only on desktop, and not on mobile. After i switch the project on Blazor, the image is not visible on desktop and mobile. I saw that nicepage as a global css file, and a specific css file for the html page. So i add them into the razor page
<link rel="stylesheet" href="nicepage.css" media="screen"> <link rel="stylesheet" href="home.css" media="screen">
But nothing happened.
So i would like to know if anyone has managed to create html page with Nicepage, and then use it in a Blazor project?
Thank you.
Blazor can be evil :). It works best with CSS (switching classes according to that field etc.) in my opinion. So if you want to display something on desktop do:
1. code in CSS like
#media (max-width: 992px){
.nameOfClass {
display:none;
}
}
2. Javascript:
Do simple model, inject IJSRuntime, invoke it, create function and use it as property in html part
Model -
public class WindowDimension
{
public int Height { get; set; }
public int Width { get; set; }
}
Inject IJSR -
#inject IJSRuntime JS at top of .razor page
Invoke e.g. in OnInitialize also be aware of naming. I had some issues when I had it like HeightOfWindow etc.
#code{
int Height { get; set; }
int Width { get; set; }
protected override async Task OnInitializedAsync()
{
var dimension = await JS.InvokeAsync<WindowDimension>("getWindowDimensions");
Height = dimension.Height;
Width = dimension.Width;
}
}
Create function in JS (can be only code in some JS file + do not forget to put in index file.
window.getWindowDimensions = function () {
return {
width: window.outerWidth,
height: window.outerHeight
};
};
HTML
<div style:"width: #Height">.....</div>

How to update HREF after anchor gets clicked in Blazor?

Trying to replace HREF upon click on Anchor with Blazor.
So in pseudo;
click => calls function => replaces HREF => triggers open event, but targets new HREF
couldn't make it happen, what should be the syntax?
#context.FileName
Side note
Please do not reference https://github.com/aspnet/AspNetCore/issues/5545. I'm asking how to replace the HREF value with an external address which is irrelevant to that issue since I'm OK to use javascript: void(0) at this point.
Thanks to #daniherrera I started to look into the right places and figured it out the answer in here
[Inject] public NavigationManager NavigationManager { get; set; }
[Inject] public IJSRuntime JsRuntime { get; set; }
public async Task NavigateToUrlAsync(string url, bool openInNewTab)
{
if (openInNewTab)
{
await JsRuntime.InvokeAsync<object>("open", url, "_blank");
}
else
{
NavigationManager.NavigateTo(url);
}
}

Get the same display using an ActionLink inside Html.BeginForm and simple <a> tag

In my ASP.NET MVC 5 website I have a menu with two types of files: actual pages returned from the controllers and pdf files that you can view in the navigator. Since my menu is created dynamically (it varies according to Active Directory rights) I have to distinguish which type is which (Document or Page), and this means that according to the file type you click, it will not result in the same action.
To show you, imagine there is a List<DocumentModel> documents and the following to treat the information:
<ul>
#foreach (var document in documents)
{
<li>
#if (document.type.Equals("Document"))
{
using (Html.BeginForm("DisplayPDF", "Navigation", new { pdfName = document.link }, FormMethod.Post))
{
#Html.ActionLink(document.docName, "DisplayPDF", null, new {id="linkStyle", #class = "saveButton", onclick = "return false;" })
}
}
else
{
//This link is different then the one above visually
<span class="glyphicon glyphicon-file"></span>#document.docName
}
</li>
</ul>
<!--This script allows to submit the form, and treat the action of DisplayPDF-->
<script>
$(document).ready(function () {
$('.saveButton').click(function () {
$(this).closest('form')[0].submit();
});
});
</script>
DocumentModel is as follows:
public class DocumentModel
{
public long idDocument { get; set; }
public long idCategory { get; set; }
public string docName { get; set; }
public string link { get; set; }
public string type { get; set; }
}
Finally my DisplayPDF method is the following:
public FileContentResult DisplayPDF(string pdfName)
{
var fullPathToFile = #"Your\Path\Here" + pdfName;
var mimeType = "application/pdf";
var fileContents = System.IO.File.ReadAllBytes(fullPathToFile);
return new FileContentResult(fileContents, mimeType);
}
Now as you can see in the Razor view I displayed, there are two types of clickable links. One is only a controller redirection, whereas the second calls the DisplayPDF method and then returns a PDF page. The problem I'm having is that these links are displayed differently, and I don't know how to have the same display for both.
To synthesize my question : how to display the same using #Html.ActionLink() and 'a' tag, knowing that currently, the 'a' tag has the proper display?
Update I modified some code as to give IDs to <a> tag and #Html.ActionLink, then I added this css in stylesheet:
#linkStyle {
margin-left: 25px;
color: antiquewhite;
}
But I still have a different display
UPDATE 2 I think that the problem of display come from the BeginForm method, any ideas to fix this?

Categories

Resources