GithubHelp home page GithubHelp logo

dpaquette / taghelpersamples Goto Github PK

View Code? Open in Web Editor NEW
378.0 40.0 98.0 3.59 MB

A set of sample tag helpers for ASP.NET Core MVC

Home Page: http://taghelpersamples.azurewebsites.net/

License: Other

C# 6.21% HTML 5.22% JavaScript 74.76% CSS 13.74% Makefile 0.06%
taghelpers aspnetcore

taghelpersamples's Introduction

AppVeyor: Build status

Tag-helper-samples

TagHelper Samples running on Azure. Sample tag helpers that do useful work.

To use the Bootstrap AlertTagHelper (authored by Rick Strahl) add Font Awesome. The sample project adds FA to the Views\Shared_Layout.cshtml file.

Click the Summary menu item to see the tag helpers in action. From the home link, select a tag helper to see a code snipet and the resulting UI.

Try it in your project

Bootstrap Tag Helpers

Bootstrap Tag Helpers NuGet Badge

The Bootstrap Tag Helper samples are available on Nuget.

dotnet add package TagHelperSamples.Bootstrap

Then add the tag helpers to your _ViewImports.cshtml file:

@addTagHelper "*, TagHelperSamples.Bootstrap"

Markdown Tag Helpers

Markdown Tag Helpers NuGet Badge

The Markdown Tag Helper samples are available on Nuget.

dotnet add package TagHelperSamples.Markdown

Then add the tag helpers to your _ViewImports.cshtml file:

@addTagHelper "*, TagHelperSamples.Markdown"

Authorize Tag Helper

Authorization Tag Helpers NuGet Badge

The Authorize Tag Helper is available on Nuget.

dotnet add package TagHelperSamples.Authorization

Then add the tag helpers to your _ViewImports.cshtml file:

@addTagHelper "*, TagHelperSamples.Authorization"

taghelpersamples's People

Contributors

bryant1410 avatar dpaquette avatar evalex avatar kwhjvdkamp avatar manojkulkarni30 avatar maximrouiller avatar misterjames avatar mm98 avatar patrickniezen avatar peterblazejewicz avatar rdeveen avatar rick-anderson avatar rickstrahl avatar wawrzyn321 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

taghelpersamples's Issues

Upgrade to Beta8

ASP.NET 5 Beta 8 was released today with a couple breaking changes related to tag helpers.

Tag Helper for Bootstrap Panel

@dpaquette I would like contribute tag helper for bootstrap panel. Can i submit a pull request for it ?

Structure:

<panel type="info">
    <panel-title>Info Panel</panel-title>
    <panel-body>
        <p>
            Learn how to build ASP.NET Core apps that can run anywhere.
        </p>
    </panel-body>
</panel>

End Result:

<div class="panel panel-info">
	<div class="panel-heading">
		<h3 class="panel-title">Info Panel</h3>
       </div>
	<div class="panel-body">
		<p>
			Learn how to build ASP.NET Core apps that can run anywhere.
		</p>
	</div>
</div>

Not authorize tag helper addition

For the authorize tag helpers, a typical case that I didn't see covered would be needing to show one section of html to authorized users and show a different section of html to non-authorized users. Maybe something like a asp-authorize-anonymous.

I didn't see a way of doing this with current tag helpers but it could be useful and effectively eliminate if-elses in razor based on user being logged in.

text-entry throws System.NullReferenceException when For value is null

My template is:

@model NSysWebTest.Web.ViewModels.Products.ProductCategoryViewModel
<text-entry id="Name" label-text="Name" for="Name"></text-entry>
<text-entry id="Note" label-text="Note" for="Note"></text-entry>

Template model ProductCategoryViewModel is

new ProductCategoryViewModel{
    Name = "Test",
    Note = null
};

I'm getting an error System.NullReferenceException while rendering a template on a line with Note

Form inside Modal

How can we have an structure like this?

<modal title="Modal title">
    <form asp-controller="Controller" asp-action="Action" method="post">
        <modal-body>

            <div class="form-horizontal">
                <div class="form-group">
                    <label asp-for="Nome" class="control-label col-md-2">Nome:</label>
                    <div class="col-md-10">
                        <input asp-for="Nome" type="text" class="form-control" />
                    </div>
                </div>
            </div>

        </modal-body>
        <modal-footer>
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>
        </modal-footer>
    </form>
</modal>

The modal was correctly generated, but the form was removed (as expected).
I've tried to create another custom helper to form like

/// <summary>
    /// A Bootstrap modal dialog
    /// </summary>
    [RestrictChildren("modal-body", "modal-footer", "form")]
    public class ModalTagHelper : TagHelper
    {
        /// <summary>
        /// The title of the modal
        /// </summary>
        public string Title { get; set; }

        /// <summary>
        /// The Id of the modal
        /// </summary>
        public string Id { get; set; }

        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            var modalContext = new ModalContext();
            context.Items.Add(typeof(ModalTagHelper), modalContext);

            await output.GetChildContentAsync();

            var template =
$@"<div class='modal-dialog' role='document'>
    <div class='modal-content'>
      <div class='modal-header'>
        <button type = 'button' class='close' data-dismiss='modal' aria-label='Close' modal-close-action><span aria-hidden='true'>&times;</span></button>
        <h4 class='modal-title' id='{context.UniqueId}Label'>{Title}</h4>
      </div>
        <div class='modal-body'>";

            output.TagName = "div";
            output.Attributes.SetAttribute("role", "dialog");
            output.Attributes.SetAttribute("id", Id);
            output.Attributes.SetAttribute("aria-labelledby", $"{context.UniqueId}Label");
            output.Attributes.SetAttribute("tabindex", "-1");
            var classNames = "modal fade";
            if (output.Attributes.ContainsName("class"))
            {
                classNames = string.Format("{0} {1}", output.Attributes["class"].Value, classNames);
            }
            output.Attributes.SetAttribute("class", classNames);
            output.Content.AppendHtml(template);
            if (modalContext.Body != null)
            {
                output.Content.AppendHtml(modalContext.Body);
            }
            output.Content.AppendHtml("</div>");
            if (modalContext.Footer != null)
            {
                output.Content.AppendHtml("<div class='modal-footer'>");
                output.Content.AppendHtml(modalContext.Footer);
                output.Content.AppendHtml("</div>");
            }

            output.Content.AppendHtml("</div></div>");
        }
    }

    /// <summary>
    /// The modal-footer portion of Bootstrap modal dialog
    /// </summary>
    [HtmlTargetElement("modal-footer", ParentTag = "modal")]
    [HtmlTargetElement("modal-footer", ParentTag = "form")]
    public class ModalFooterTagHelper : TagHelper
    {
        /// <summary>
        /// Whether or not to show a button to dismiss the dialog. 
        /// Default: <c>true</c>
        /// </summary>
        [HtmlAttributeName("show-dismiss")]
        public bool ShowDismiss { get; set; } = true;

        /// <summary>
        /// The text to show on the Dismiss button
        /// Default: Cancel
        /// </summary>
        [HtmlAttributeName("dismiss-text")]
        public string DismissText { get; set; } = "Cancel";

        /// <summary>
        /// A classe CSS a ser aplicada no botão de dismiss.
        /// Não é necessário aplicar btn
        /// </summary>
        [HtmlAttributeName("dismiss-css-class")]
        public string DismissCssClass { get; set; } = "btn-default btn-100";


        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            if (ShowDismiss)
            {
                output.PreContent.AppendFormat(@"<button type='button' class='btn {0}' data-dismiss='modal' modal-close-action>{1}</button>", DismissCssClass, DismissText);
            }
            var childContent = await output.GetChildContentAsync();
            var footerContent = new DefaultTagHelperContent();
            if (ShowDismiss)
            {
                footerContent.AppendFormat(@"<button type='button' class='btn {0}' data-dismiss='modal' modal-close-action>{1}</button>", DismissCssClass, DismissText);
            }
            footerContent.AppendHtml(childContent);
            var modalContext = (ModalContext)context.Items[typeof(ModalTagHelper)];
            modalContext.Footer = footerContent;
            output.SuppressOutput();
        }
    }

    /// <summary>
    /// The modal-body portion of a Bootstrap modal dialog
    /// </summary>
    [HtmlTargetElement("modal-body", ParentTag = "modal")]
    [HtmlTargetElement("modal-body", ParentTag = "form")]
    public class ModalBodyTagHelper : TagHelper
    {
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            var childContent = await output.GetChildContentAsync();
            var modalContext = (ModalContext)context.Items[typeof(ModalTagHelper)];
            modalContext.Body = childContent;
            output.SuppressOutput();
        }
    }

But had no success...

How can I fix it?

Authorise TagHelper in For Loop

Hi,

Nice article, Very easy to use.

Just one question , while using this resource based Tag helper in for loop , it will check 10 time for Delete operation in database right ?

Single condition of Delete in for loop it will check 10 times in loop.

Do you have any simplified solution to that?

Regards,
jigar

Suggested way to implement Alerts

Hi David, thanks for amazing Job!

I have seen working the sample where the TagHelper works properly, but I would like to know what is the suggested way to show the Alert TagHelper after a callback? For example, when the "done" method in the $Ajax callback.

Thanks!

The ModalFooterTagHelper lacks await in ProcessAsync implementation

https://github.com/dpaquette/TagHelperSamples/blob/master/TagHelperSamples/src/TagHelperSamples.Bootstrap/ModalFooterTagHelper.cs#L24-L38

TagHelperSamples/TagHelperSamples/src/TagHelperSamples.Bootstrap/
ModalFooterTagHelper.cs(24,36): 
DNXCore,Version=v5.0 warning CS1998: 
This async method lacks 'await' operators and will run synchronously. 
Consider using the 'await' operator to await non-blocking API calls, 
or 'await Task.Run(...)' to do CPU-bound work on a background thread.

Most probably that could be changed to use just sync version as in toggle implementation:
https://github.com/dpaquette/TagHelperSamples/blob/master/TagHelperSamples/src/TagHelperSamples.Bootstrap/ModalToggleTagHelper.cs#L20-L24
Thanks!

Version for .NET Core 1.1?

I've been looking around for a cleaner way of implementing authorizations rather than dumping code into my razor views. Feels too much like classic ASP with VBScript. This tag helper would help immensely with it, but my project is limited to 1.1. Is there a way to use this tag helper with 1.1? I see an issue for upgrading to 2.0, but I can't find a version previous to that.

Automate deployment

Can we set this up so the website automatically updates when PRs are merged to the master branch?

Better bundling with asp.net mvc 6

Hi, I have a solution for better bundling support. I use gulp include (https://www.npmjs.com/package/gulp-include) to define bundles which are built in the deployment process. For development I want to include the raw files without minification.

e.g wwwroot/scripts/main.bundle

 //= include /js/schemas/controllers.list.js
 //= include /js/app.js

to include this bundle files you can use the following code:

<environment names="Development">
    <script-bundle file="~/scripts/main.bundle"></script-bundle>
</environment>
<environment names="Staging,Production">
    <script-bundle file="~/scripts/main.bundle" bundle="true" minified="true"></script-bundle>
</environment>

You can find the source code here: https://gist.github.com/SebastianStehle/258998d761dad255228c

The advantage of this solution is, that there is only one place where to define the bundles. In contrast to this solution: http://www.jeffreyfritz.com/2015/05/where-did-my-asp-net-bundles-go-in-asp-net-5/

Update to RC2

RC2 has finally landed...time to update the samples

Bootstrap 4 +

The nav-link Tag Helper does not work correctly with Bootstrap 4 beta 3. The selected navigation is the same as the rest of the navigation.

My Bad I had to overwrite active to see any difference. Below is what I added to my custum css to get the results I was looking for.

.navbar-nav > .active > a {
color: black;
font-weight: bold;
}

.nav-item > a:hover {
color: black;
font-weight: bold;
}

Example of Integration tests

An example showing how to do integration tests for tag helpers. See the MVC6 repo for ideas on how to actually do this

Authorize tag helper

Create a tag helper that can only renders a block of HTML if a user has the specified Roles or meets the requirements for a specified Policy

Markdown helper should not use p tag wrapper

Markdown generates p tags, it doesn't make sense to force p tags inside of a wrapper p tag. The wrapper tag really should be div, article, section, or even span. (or even literal text and no tag at all, if that's an option for tag helpers)

NavLinkTagHelper doesn't output A inside LI

In RTM, NavLinkTagHelper doesn't output A inside LI, so for:

<nav-link asp-controller="Home" asp-action="About">About</nav-link>

I'm actually getting:

<li class="active">About</li>

Any idea? thanks!

Authorize taghelper issue

Hi there,

I tried to upgrade my asp.net core 2.2 app to asp.net core 3.0 preview 7 but I noticed I get the following error when using asp-authorize attribute

Reference to type 'IAuthorizeData' claims it is defined in 'Microsoft.AspNetCore.Authorization', but it could not be found

Bug TextEntryTagHelper and TagBuilder.ToString()

Well the bug is pretty obvious: on lines 82 and 92, the ToString() will return the name of the class rather than the content of the tag builder.

I did the workaround Like that:

var writer = new System.IO.StringWriter(); ctl.WriteTo(writer, new HtmlEncoder()); sb.AppendLine(writer.ToString());

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.