ASP.net navbar with bootstrap - asp.net-mvc-4

Good evening every one .
i would like to add an image near a navbar , but i'm not able to imitate the code propose by bootstrap , because ASP.net use helpers of razor while in bootstrap web site there use diretly an html code.
please how could i adapt this in ASP.net

You should try following code instead of the HTML of bootstrap,
where imagepath is your image path.
Razor Syntax Rules for C#:
Razor code blocks are enclosed in #{ ... }
Inline expressions (variables and functions) start with #
C# code is case sensitive
Variables are declared with the var keyword
Code statements end with semicolon
Strings are enclosed with quotation marks
C# files have the extension .cshtml
#model YourProject.Models.ImageModel
#{
imagePath= "xyz/xyz.jpg"
}
#if(imagePath != ""){
<img src="#imagePath" alt="Image Name" width="200px" />
}
If you take image path from model then you try following code:
#model YourProject.Models.ImageModel
#if(Model.Photo != null && Model.Photo != ""){
<img src="#Url.Content(#Model.Photo)" alt="#Model.AlternateText" />
}
If you don't understand then please refer following link:
https://learn.microsoft.com/en-us/aspnet/web-pages/overview/ui-layouts-and-themes/9-working-with-images

Related

Razor template/component solution that supports child Razor markup

Is there a template/component solution in ASP.NET Core Razor, that supports inner Razor markup?
Here's a use case:
1. Say I have some repetitive markup for example "a div with nice borders, shadows and two buttons at the bottom"
2. Obviously this markup has a common "header" and a "footer" in the HTML code
3. I need to pass arbitrary Razor markup to insert between header and footer. Not just a model object - but some actual markup that will be rendered between header and footer. I can't use foreach because this markup is different every time - it can be text-content, a form, an image, or some complicated Razor-rendered stuff.
Basically I'm looking for a "Surround this Razor with more Razor" templating solution
Something like:
#{
//this function renders my beautiful box
Func<dynamic, IHtmlContent> myFunction = #<div class="relative flex flex-col rounded-2xl border border-gray-200 bg-white p-8 shadow-sm">
#item
</div>;
}
<!-- and then I call it passing some Razor as input -->
#myFunction(
<ul>
<li>#SomeRazorMethod()</li>
</ul>
);
Something like a Layout - but the one I can use multiple times on the same page.
Is there anything like that? This is a pretty common componentizing tool - "wrap my markup with other markup" - that is present in other templating engines (React, Vue, etc), but apparently not in Razor.
Just to be clear: I'm looking for a Razor-based solution, not a C#-based one. So that my header-footer markup stays in markup files (.cshtml), not in C# files that will have hard-coded HTML magic strings.
Based on your example, this might help.
#functions {
public static IHtmlContent MyBox(dynamic item, Func<dynamic, IHtmlContent> template)
{
var html = new HtmlContentBuilder();
html.AppendHtml("<div class='bestcss'>");
html.AppendHtml(template(item));
html.AppendHtml("</div>");
return html;
}
}
#MyBox(null, #<div class='innercss'>#(10 == 12 ? "MyTest Equals" : "No Equal") hello</div>)
And if you like to pass modeldata, it will be:
#MyBox(customerdata, #<div class='innercss'>#(10 == 12 ? "MyTest Equals" : "No Equal") hello #item.FirstName</div>)
I have used some arbitrary if condition for testing.
You can use Partial Pages or Views which are Razor files containing snippets of HTML and server-side code to be included in any number of pages or layouts.
Just like standard Razor pages, partial pages support the #model
directive specifying the type for the partial's data model. All of the
rendering methods have overloaded versions that take a model to be
consumed in the partial.
#Shah's answer got me one step closer to a solution, however, it seems like the the actual question I'm trying to solve is "can I pass Razor markup as an input parameter".
Turns out you can, you just have to put # in front of it:
#{
void MyFunc(Func<object, IHtmlContent> template)
{
<div>#template(null)</div>
}
}
#{ MyFunc(#<div>The ID is: #Model.Id</div>); }
<!-- mind the '#' before the 'div' -->

ASP.NET Core 3.1 Razor - Is it possible to turn a String into a Hyperlink using Html.Raw

Is it possible to turn a String into a Hyperlink using Html.Raw. What would the code for this be?
I'm trying to embed an <a> Tag into a Razor Page with the following:
#{
string strText = "<title>Link Test</title><a class=\"nav-link text-dark\" target=\"_new\" asp-
area=\"Test\" asp-controller=\"Test\" asp-action=\"ViewFile\" asp-route-Id=1> View File Test</a>";
}
#Html.Raw(strText)
My page just shows "View File Test" without a link.
When I view the page source in my browser I see the following:
<title>Link Test</title><a class="nav-link text-dark" target="_new" asp-area="Test" asp-controller="Test" asp-action="ViewFile" asp-route-Id=1> View File Test</a>
When I copy the above and paste it to my razor page, all works well.
Just for fun, I have also tried the following and get the same result:
#{
string strText = "<title>Link Test</title><a class=\"nav-link text-dark\" target=\"_new\" asp-
area=\"Test\" asp-controller=\"Test\" asp-action=\"ViewFile\" asp-route-Id=1> View File Test</a>";
}
<text>#strText</text>
The following example below works fine, but not the above. I thought maybe it had to do with the embedded quotes
#{
string strText = "My Text My link.";
}
#Html.Raw(strText)
For HtmlHelper.Raw Method , the parameter is the HTML markup, however asp-area and asp-controller are the Anchor Tag Helper attributes. HTML code, or actually any text, returned from methods is not processed by the Razor engine, so you cannot use HTML tag helpers here.
You could try to use #Html.ActionLink or #Url.Action helper methods as shown:
#{
string strText = "<title>Link Test</title><a class=\"nav-link text-dark\" target=\"_new\" href=\""+Url.Action("ViewFile","Test" ,new { Area="Test",Id=1})+"\" >View File Test</a>";
}
the generated url will be https://localhost:44348/Test/Test/ViewFile?Id=1.
register routes as below:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "areaRoute",
// if you don't have such an area named as `areaName` already,
// don't make the part of `{area}` optional by `{area:exists}`
pattern: "{area}/{controller=Home}/{action=Index}");
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
Reference:
https://stackoverflow.com/a/35579040/10201850
https://stackoverflow.com/a/53147778/10201850
The main reason your solution with asp tags will not work because they (tag helpers) are compiled at run time into your existing views.
At runtime compilation, your string is getting compiled as a string and tags inside that are being ignored obviously because compiler is unaware of them.
But when you use html attributes like anchor tag, it will work fine because that gets parsed by your browser.
Keep in mind that in Razor, asp- prefixed attributes for tags are somehow rendered at server side. This properties/attributes are not from HTML5.
Answer: Yes, it is possible, but it must be valid HTML.

Show hide html attribute based on model var in Razor - "#" must be followed by a valid code block

I am using razor to show/hide page content based on variables in the model:
#if (Model.TicketShown == null)
{
#:<div id="ticket-section">
} else {
#:<div id="ticket-section" style="display:none">
}
//More Code
#:</div>
I have been using it for a while, but today I am getting the error '"#" must be followed by a valid code block' just on the closing tag. I am using the syntax elsewhere and it works fine.
Why and is there a more elegant way of doing this? Thanks
#: is meant to be used inside code blocks (see Explicit line transition), your #:</div> might not be inside one. You could use Html.Raw as alternative (e.g. #Html.Raw("</div>")).
With the help of the ?: operator, you could also rewrite the if as follows:
<div id="ticket-section" style=#(Model.TicketShown == null ? "" : "display:none")>
...
</div>

How do I allow my ASP.NET Core tag helpers to be self-closing

I have written a tag helper that I can use as follows...
<mytaghelper attr1="jim"></mytaghelper>
I would like to be able to shorten this to just...
<mytaghelper attr1="jim">
...or at least...
<mytaghelper attr1="jim"/>
However, I can't get this to work. Here is some sample code for the Process method...
public override void Process(TagHelperContext context, TagHelperOutput output) {
output.TagName = "div";
output.PreContent.SetHtmlContent("<div>");
output.Content.SetHtmlContent("OUTPUT HTML GOES HERE");
output.PostContent.SetHtmlContent("</div>");
output.Attributes.Clear();
}
I have tried adding a TagStructure setting to the HtmlTargetElement attribute on the class...
[HtmlTargetElement("mytaghelper", TagStructure = TagStructure.WithoutEndTag)]
...but it doesn't seem to make any difference. <mytaghelper attr1="jim"/> generates <div /> and <mytaghelper attr1="jim"></mytaghelper> generates <div></mytaghelper>.
If I set the TagStructure to NormalOrSelfClosing then included a closing tag works, but <mytaghelper attr1="jim"/> gives an empty <div />
Anyone able to explain what I need to do?
TagStructure.WithoutEndTag is able to write the tag with only a start tag or self-closing, but the output would be <div > or <div/> . Self-closing anchor tags are not valid HTML, so you wouldn't want to create one, but you might want to create a tag helper that's self-closing. Tag helpers set the type of the TagMode property after reading a tag. Add the below code line Inside the process method:
output.TagMode = TagMode.StartTagAndEndTag;
Take a moment to read Author Tag Helpers in ASP.NET Core which covers this perfectly .
The correct syntax is:
[HtmlTargetElement("mytaghelper", TagStructure = TagStructure.WithoutEndTag)]
Which should be applied to the taghelper class, not the Process method. You may already be doing that, but it wasn't clear in your question. I believe you still must use the self-closing tag syntax (/>) for it work, though.

How can I use #Html.RenderPartial inside Ajax.Beginform?

Is it possible to use #Html.RenderPartial inside #using(Ajax.BeginForm) code block?
It doesn't work if I use #Html.RenderPartial, and it works if I put whole of razor code directly inside #using(Ajax.BeginForm) block.
Could anyone please suggest if that's possible or not?
If the Html.RenderPartial is right after the #using(Ajax.BeginForm(...)) then you don't need to prefix the call to Html.RenderPartial with # as razor understands you are still in the same code block.
So, this works fine:
#using (Ajax.BeginForm(...)) {
Html.RenderPartial("_PartialView", Model);
<p>after partial view inside the ajax form</p>
}
If between the `#using(Ajax.BeginForm(...)) and the render partial you have some html, then razor will end the code block before you call RenderPartial and you will need to do this:
#using (Ajax.BeginForm(new AjaxOptions())) {
<div>
<h3>partial view inside the ajax form</h3>
#{ Html.RenderPartial("_PartialView", Model); }
</div>
}
Also notice that Html.RenderPartial is a method that returns void and internally calls Write, so the syntax for using it is slightly different than when you use Html.Partial, that's why you need to surround it with "#{" (when not in a code block already) and end it with semicolon. See this question