Categories
Technology

Creating Static Images in Blazor: A Complete Guide

Blazor is a popular web framework that allows developers to create web applications using C# instead of JavaScript. It provides a simple, elegant, and efficient way to build client-side applications that run in any modern web browser. In this article, we will be exploring the creation of static images in Blazor. We will cover the basics of how to add and display images in a Blazor application, as well as some advanced techniques for optimizing images for better performance.

Understanding Image Formats

Before we dive into the specifics of creating static images in Blazor, it is important to understand the different image formats available and their respective advantages and disadvantages. There are three primary image formats used on the web: JPEG, PNG, and GIF.

JPEG is a lossy image format that is best suited for photographs and other complex images with many colors. It is a compressed image format that reduces file size by removing some of the image’s original data. While this compression can result in a loss of image quality, it can also greatly reduce file size, making it ideal for use on the web.

PNG is a lossless image format that is best suited for images with fewer colors, such as logos, icons, and other graphics. Unlike JPEG, PNG compression does not remove any image data, resulting in higher image quality but larger file sizes.

GIF is a lossless image format that supports animation. It is best suited for simple animations and other small, lightweight graphics.

Adding Images to a Blazor Application

Adding images to a Blazor application is a straightforward process. First, you need to include the image file in your project’s wwwroot folder. This folder is used to store static files that can be served directly by the web server.

Once you have added the image file to your project, you can reference it in your HTML or Razor code using the  tag. For example, the following code displays an image named “logo.png” in a Blazor component:

<img src=”/logo.png” alt=”My Logo” />

In this code, the “src” attribute specifies the location of the image file, and the “alt” attribute provides alternative text that is displayed if the image cannot be loaded or is inaccessible to visually impaired users.

Optimizing Images for Better Performance

While adding images to a Blazor application is easy, it is important to optimize them for better performance. Large, unoptimized images can slow down the loading time of your web pages and negatively impact the user experience. There are several techniques that you can use to optimize images in a Blazor application:

Reduce Image Size: One of the simplest ways to optimize images is to reduce their size. This can be done by compressing the image using a tool like TinyPNG or by resizing the image to a smaller resolution. This reduces the file size of the image, making it faster to load.

Use Responsive Images: Responsive images are images that are served in different sizes depending on the screen size of the device. This ensures that the image is always displayed at the appropriate size and resolution, improving the user experience.

Lazy Loading: Lazy loading is a technique that defers the loading of non-critical resources, such as images, until they are needed. This can greatly reduce the initial load time of your web pages and improve performance.

Conclusion

In conclusion, creating static images in Blazor is a simple process that involves adding the image file to your project’s wwwroot folder and referencing it in your HTML or Razor code using the tag. However, it is important to optimize your images for better performance by reducing their size, using responsive images, and lazy loading.

Additionally, if you want to explore more about the topic, you can check out the informative blog post titled “The Ultimate Guide to Blazor Forms and Validation” for further insights and guidance.

Categories
Technology

The Ultimate Guide to Blazor Forms and Validation 

This blog will explain how to implement Forms and Validation in Blazor. The EditForm component aids in the validation of webforms and data annotations.

Let’s look at how the EditForm component handles data annotation validation.

Consider the Student class file below.

All of the class properties are marked with the [Required] attribute in this case. It specifies that the value of the data field is required. [MinLength(3)] attributes are assigned to the Name. It specifies the shortest string data allowed in name. The [Range] attribute is assigned to the DateOfBirth property. The range has been set to “1/1/2000” to “1/1/2010”. As a result, the date of birth should be between “1/1/2000” and “1/1/2010”. Also, the ErrorMessage property has been set, so if the user enters an invalid date of birth, the error message will be displayed.

Demo.cs
using System.ComponentModel.DataAnnotations;

namespace SampleBlazorApp.Data
{ 
    public class Student
    {
        [Required]
        [MinLength(3)]
        public string Name{ get; set; }
        
        [Required]
        public string Gender { get; set; }

        [Required]
        [Range(typeof(DateTime), "1/1/2000", "1/1/2010",
        ErrorMessage = "The date of birth should between 1/1/2000 to 1/1/2010")]
        public DateTime DateOfBirth { get; set; } = Convert.ToDateTime("1/1/2000");
    }
}

The code for a razor component is as follows. A form attribute is created by the EditForm element. It displays the form element. In the @code area, the student model is created. The student model is assigned the Model attribute in the EditForm component. As a result, it binds the student model to the form. The SaveData method is assigned to the EditForm‘s OnValidSubmit attribute. The SaveData  method will be executed if no validation errors occur. For example, if any of the input fields are empty, the validation summary will display the message like “The name field is required”. That means the validation process isn’t finished. The SaveData method is not called in such cases.

In the code below, an InputText component is added to add and edit string values. The InputDate component has been added to collect the date of birth value. The @bind-Value directive attribute aids in binding model values to the component value properties InputText and InputDate.

index.cshtml
@page "/"
@using SampleBlazorApp.Data

<EditForm Model="@student" OnValidSubmit="SaveData">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <p>
        First Name:
        <InputText @bind-Value="@student.FirstName"></InputText>
    </p>
    <p>
        Last Name:
        <InputText @bind-Value="@student.LastName"></InputText>
    </p>

    <p>
        Gender:
        <InputText @bind-Value="@student.Gender"></InputText>
    </p>

    <p>
        Date of Birth:
        <InputDate @bind-Value="@student.DateOfBirth"></InputDate>
    </p>

    <p>
        Address:
        <InputText @bind-Value="@student.Address"></InputText>
    </p>
    <button type="submit">Submit</button>
</EditForm>

@code {
    private Student student = new Student();

    private void SaveData()
    {
        // data save code
    }
}

The following is the output of the above code. Here you can see that when the user clicks on the submit button it gives a summary error message. The error message disappears when the user enters the correct values.

blazor validation 1

Must True Validation

The user may be required to acknowledge something like ‘I accept the terms and conditions’ at times. If this is the case, the checkbox must be selected before submitting the form.  Let’s look at how to do that with data annotation validation.

A demo class file is provided below. It has two properties: Name and IsAccepted. The property IsAccepted must be true. So, the range validation attribute was used here. The data type bool has been specified. The minimum and maximum values are both set to “true.” If it is false, it means the user did not check the checkbox, and the error message will be displayed.

Demo.cs

using System.ComponentModel.DataAnnotations;

namespace SampleBlazorApp.Data

{
    public class Demo
    {
        [Required]
        [MinLength(2)]
        public string Name { get; set; }

        [Range(typeof(bool), "true", "true", 
            ErrorMessage = "Accept the terms and conditions")]            
        public bool IsAccepted { get; set; }
    }
}

The following is a razor page code. 

index.razor
@page "/"
@using SampleBlazorApp.Data

<EditForm Model="@demo" OnValidSubmit="SaveData">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <p>
        Name:
        <InputText @bind-Value="@demo.Name"></InputText>
    </p>
    <p>
        <InputCheckbox @bind-Value="@demo.IsAccepted"></InputCheckbox> I accept the terms and conditions
    </p>

    <button type="submit">Submit</button>
</EditForm>

@code {
    private Demo demo = new Demo();

    private void SaveData()
    {
        // data save code
    }
}

The image below is the result of the above code. The range validation is demonstrated here.

blazor validation 2

Validation for Specific Field

The preceding examples demonstrate how to display the error message in summary. However, if you want to display a specific error message, you can use the <ValidationMessage> component. The code below demonstrates the specific field validation. The <ValidationMessage> attribute has been added next to the Name and Age textboxes.

index.cshtml
@page "/"
@using SampleBlazorApp.Data

<EditForm Model="@demo" OnValidSubmit="SaveData">
    <DataAnnotationsValidator />

    <p>
        Name:
        <InputText @bind-Value="@demo.Name"></InputText>
        <ValidationMessage For="@(() => demo.Name)" />
    </p>
    <p>
        Age: 
        <InputNumber @bind-Value="@demo.Age" ></InputNumber>
        <ValidationMessage For="@(() => demo.Age)" />
    </p>

    <button type="submit">Submit</button>
</EditForm>

@code {
    private Demo demo = new Demo();

    private void SaveData()
    {
        // data save code
    }
}

The above code produced the following result. When the user enters the age 5 here, the error message appears right next to the age textbox.

blazor validation 3

Handle Form Submission

To handle the form submission, the EditForm provide following callbacks

OnValidSubmit – This will call the assigned event handler when the user has entered all valid entries

OnInvalidSubmit – This will call the assigned event handler when the input value is no or any value is invalid

OnSubmit – This will call the assigned event handler whether the form is valid or not.

Built-in form component

The Blazer framework provides some built-in input components to obtain input values. The following is a list of built-in form elements

Input ComponentRendered Element
InputCheckbox<input type=”checkbox”>
InputDate<input type=”date”>
InputFile<input type=”file”>
InputNumber<input type=”number”>
InputRadio<input type=”radio”>
InputRadioGroupGroup of child InputRadio
InputSelect<select>
InputText<input>
InputTextArea<textarea>

Conclusion

From this blog you can understand how form and data annotation validation works in Blazor. Also, You can also find coding examples for various types of validation. I hope you find this blog useful.

Read our blog for valuable insights on Static Image in Blazor

Categories
ASP.NET Core

Developer Exception Page in ASP.NET Core

The developer exception page is a one of the error handling processes in ASP.Net Core. It will give you complete details about the exception.

To enable the Developer exception page app.UseDeveloperExceptionPage(); should be added in Configure method in Startup.cs file. The  app.UseDeveloperExceptionPage(); must appear before the middleware  which needs to handle the exception.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
    app.UseDeveloperExceptionPage();
    }
}

The Developer Exception  Page will have the following Information

  • Stack
  • Query
  • Cookies
  • Headers
  • Routing

Let’s look at a small example of how the exception is displayed in the browser without app.UseDeveloperExceptionPage() and app.UseDeveloperExceptionPage(). I  have commanded the exception handling process from the Configure method in Startup.cs 

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    //if (env.IsDevelopment())
    //{
    //    app.UseDeveloperExceptionPage();
    //}
    //else
    //{
    //    app.UseExceptionHandler(“/Error”);
    //    app.UseHsts();
    //}

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
    endpoints.MapRazorPages();
    });
}

The following is a screenshot of the exception. It does not clearly show what the exception is.

It Just says “This page isn’t working, localhost is currently unable to handle this request. HTTP ERROR 500”

Developer Exception

In the below code I have uncommanded the exception handling process.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
    app.UseDeveloperExceptionPage();
    }
    else
    {
    app.UseExceptionHandler(“/Error”);
    app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
     endpoints.MapRazorPages();
    });
}

The following is a screenshot of the Developer Exception page. It clearly states what the exception is. It also shows on which page and line it is occurring.

pasted image

Note:

Enable the Developer Exception Page exception in the developer environment to avoid sharing the exception details in public.

If you have any questions, please leave a comment below.

Categories
ASP.NET Core

Data Binding in Blazor

Data binding is one of the most important processes in an application. Data binding is achieved through the @bind attribute in the Blazor component.

@bind attribute

The following code is an example of data binding to a textbox. This is a Blazor component code, so it contains the HTML tag and @code block in a file. Here the TextValue property value is assigned to the @bind attribute. The property value TextValue will update when the textbox loses focus. To display the updated value, the TextValue  will be displayed within the strong tag.

@page “/”

<h4>Data Binding</h4>

<input @bind=”TextValue” />

<br />
<div>
    <span>The Textbox value is: </span> <strong>@TextValue</strong>
</div>

@code {
    private string TextValue { get; set; }
}

The following is the output of the above code. Here you can see how the values are updated when the textbox loses its focus.

Data Binding in Blazor example 1

@bind:event attribute

The code below is the same as the code above. But it has @bind:event in input element. In the previous example, the textbox element updates the property variable when it loses focus. But in this example it is updated at the time of typing text using the @bind:event.

@page “/”

<h4>Data Binding</h4>

<input @bind=”TextValue” @bind:event=”oninput” />

<br />
<br />
<div>
    <span>The Textbox value is: </span> <strong>@TextValue</strong>
</div>

@code {
    private string TextValue { get; set; }
}

The following is the output of the above code. Here you can see how the values are updated when typing the text in the textbox.

Data Binding in Blazor example 2

@bind-{ATTRIBUTE} and @bind-{ATTRIBUTE}:event attributes

@bind-{ATTRIBUTE} and @bind-{ATTRIBUTE}:event helps bind the attributes. In the code below @bind-style and @bind-style:event attributes are added to the div tag. So when you set the style attribute in the textbox it will change into the div element.

@page “/”

<h4>Attribute Binding</h4>

<input type=”text” @bind=”StyleValue” />

<br />
<br />

<div @bind-style=”StyleValue” @bind-style:event=”onchange”>
    Demo Attribute Binding!
</div>

@code {
    private string StyleValue = “color:red”;
}

The following is the output of the above code. Here you can see how the div content color changes when changing the color name in the textbox.

Data Binding in Blazor exmple 3

This article explains how the @bind attribute binds value in the blazer.

If you have any questions please comment below.

Categories
ASP.NET Core

Route Templates in ASP.NET CORE Blazor

The term routing in Blazor is moving or navigating between the Blazor components. The Blazor provides a client-site routing mode. In this blog, let us see what is Route Templates in ASP.NET CORE Blazor.

In the Blazor application, the Router component is present inside the App.razor file.

The following is a default Router Component.

<Router AppAssembly=”@typeof(Program).Assembly“>
    <Found Context=”routeData”>
        <RouteView RouteData=”@routeData DefaultLayout=”@typeof(MainLayout) />
    </Found>
    <NotFound>
        <LayoutView Layout=”@typeof(MainLayout)“>
            <p>Sorry, there’s nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>

The Router component will provide the route data to the RouteView from the current navigation site. When matching is found for the requested route, the RouteView Component will populate the specified component inside the layout. If the requested route is not found, then the NotFound component will populate the content. From the above code it will display “Sorry, there’s nothing at this address.” message. Also, the user can customize the content for their needs.

Route Template

The Route Template is defined by adding the @page directive at the top of the component. @page directive will convert into RouteAttribute at the time of compiling the code. In the below snippet, the @page directive added as @page “/”. So when accessing a URL, say https://www.domainname.com/ it will display the component

@page “/”
<h1> Hello, Blazor!</ h1>
Welcome to your Blazor App lication.

https://www.domainname.com/index URL will display the below component.

@page “/ index
<h1> Hello, Index Page!</ h1>
Welcome to Index Page.

Multiple Route

A single component may have multiple route templates. Consider the following component. Here, two different @page directives are stacked in the file. So it will provide multiple routes to the same component.

@page  /BlazorRoute
@page  /AnotherBlazorRoute
<h1> Blazor Multiple Routing</h1>

https://www.domainname.com/BlazorRoute and https://www.domainname.com/AnotherBlazorRoute both URLs will display the same above component

Route parameters

@page “/BlazorRoute”
@page “/BlazorRoute/{ParameterText}”
@if  (string.IsNullOrWhiteSpace(ParameterText))
{
    <h1 >Blazor Route Without Parameter</h1 >
}
else
{
    <h1 >Blazor Route With Parameter: @ParameterText </h1>
}
@code {
    [Parameter]
    public  string ParameterText { get set; }

In the above code snippet, two @page directives are added. The first directive is to navigate without parameter and the second one is to navigate with parameter. The parameter is defined with curly brackets. [Parameter] attribute has been added to the ParameterText property variable to denote it as a component parameter.

https://localhost:44316/BlazorRoute/ will give the following output:

Blazor Route without Parameter

https://localhost:44316/BlazorRoute/My%20Parameter this URL will provide the following output.

Blazor Route with Parameter

Route constraints

@page “/BlazorRoute/{ID:int}/{TextParameter}”
<h1> The given integer value is @ID</ h1>
<h1> The given text parameter value is @TextParameter </h1>
@code {
    [Parameter]
    public  int ID { get set; }
    [Parameter]
    public  string TextParameter { get set;}
}

The above code snippet illustrates how to pass multiple parameters and route constraints. The ID parameter solely accepts the integer value[{ID:int}]. And the TextParameter will accept the string value. The following image is an output of the above code. https://localhost:44316/BlazorRoute/5/my%20parameter

Blazor Route constraints

The user needs to pass both ID and TextParameter parameters otherwise the output will show the message with the NotFound Component.

If you have any questions, please leave a comment.

Categories
ASP.NET Core

Basic Event Handling in Blazor

This article is to explain how event handling works in Blazor. The @on{event} attribute in Razor is the event handling attribute. The {event} may be any event. For example, For button @onclick is a click event. In checkbox @onchange is a change event it will trigger, when checking or unchecking the checkbox.

The following is an example for @onclick. In this code, the @page directive is added for routing. Then @result property value is added to display the result. Then the @onclick attribute is added to the button and the DisplayMessage method is assigned to it. When the user clicks the button it will display the message.

@page “/”

<div>@result</div>

<br />
<button @onclick=”DisplayMessage”>Click Here</button>

@code
{
    public string result { get; set; }

    void DisplayMessage()
    {
        result = “The button is clicked”;
    }
}

The following is an output of the above code.

Event Handling

Lambda Expressions

You can achieve the same result as above using lambda expressions.

@page “/”

<div>@result</div>

<br />
<button @onclick=”@(e=>DisplayMessage())”>Click Here</button>

@code
{
    public string result { get; set; }

    void DisplayMessage()
    {
        result = “The button is clicked”;
    }
}

Also, you can pass arguments to the @onclick method using the Lambda expression.

The following code explains how to pass arguments. Here in GetSum() method two arguments a and b are passed.

@page “/”

Sum of 1 + 2 = <strong>@result</strong>

<br /><br />
<button @onclick=”@(e=>GetSum(1, 2))”>Sum</button>

@code
{
    public int? result { get; set; }

    void GetSum(int a, int b)
    {
        result = 1 + 2;
    }
}

The following is an output of the above code.

Event Handling

This article explains what is event handling in Blazor and how to pass parameters to an event handler.

If you have questions, please leave your comments.

Categories
ASP.NET Core

Turn on CircuitOption.DetailedError in Blazor

This article is going to explain how to enable CircuitOption.DetailedError in the development environment.

Let us look at a small example. The following is the Blazor component code. It contains both HTML and @code block. GetArray() method is defined in the @code module. In it, the array is initialized with four elements.  Finally, arr [5] is assigned to the result variable so that it triggers an index outside the range exception.

@page “/”

<h4>Turn on CircuitOption.DetailedError</h4>

<button @onclick=”GetArray”>Trigger the Exception</button>

@code
{
    void GetArray()
    {
        int[] arr = new int[] { 1, 2, 3, 4 };
        int result = arr[5];
    }
}

The following screenshot illustrates how the exception is displayed in the browser. It states, Error: There was an unhandled exception on the current circuit, so this circuit will be terminated. For more details turn on detailed exceptions in ‘CircuitOptions.DetailedErrors’.

CircuitOption.DetailedError

Let us see how to enable the CircuitOption.DetailedError.

In the Startup.cs file, IWebHostEnvironment  is initialized to provide web hosting environment information. Added  IWebHostEnvironment  in Startup constructor. Finally, AddCircuitOptions has been added in the ConfigureServices method, which helps to configure circuits.

In this code _Env.Is Development () is checked to confirm if it is a development environment or not. If it is a development environment, then only it will display the detail error.

private readonly IWebHostEnvironment _env;

public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
    Configuration = configuration;
    _env = env;
}

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();

    services.AddServerSideBlazor().AddCircuitOptions(options => {
       if (_env.IsDevelopment())
      {
        options.DetailedErrors = true;
      }
    });

    services.AddSingleton<WeatherForecastService>();
}

The following screenshot illustrates how the browser displays the error after enabling a detailed error. It clearly states what the error is and shows which file it is and which line number it occurs.

CircuitOption.DetailedError in Blazor

The blog explains how to enable CircuitOption.DetailedError in the development environment.

If you have any questions, please leave a comment.

Categories
ASP.NET Core

ASP.NET Core Service Scope

Singleton vs Scoped vs Transient

This article describes the service scope in ASP.NET Core and the difference between AddSingleton, AddScoped and AddTransient  methods. Let us see the following example that shows the lifetime of the services

The following is an interface. This interface only returns a string unique ID (GuidID).

IRepository.cs

public interface IRepository
{
   string GetUniqueID();
}

The below code is an implementation of the above interface. It has a constructor MyRepository which creates a unique ID when the object is created. The final one is GetUniqueID() which returns the unique ID.

MyRepository.cs

public class MyRepository : IRepository
{
    private string uniqueID;

    public MyRepository()
    {
        uniqueID = Guid.NewGuid().ToString();
    }

    public string GetUniqueID()
    {
        return uniqueID;
    }
}

AddSingleton

AddSingleton will generate an instance when requested for the first time. Then it will use the same instance for further request.

To use the service first, you must register with the ConfigureService method in Startup.cs. This ConfigureServices method enables you to add services to the application. Here I have added AddSingleton service with Service Type IRepository and implementation MyRepository

Startup.cs

public void ConfigureServices(IServiceCollection services)
 {
     services.AddSingleton<IRepository, MyRepository>();
     services.AddControllersWithViews();
 }

The following is a HomeController code. Here the IRepository service is injected in HomeController construction. In the Index action method uniqueID is received from GetUniqueID() method and assigned to ViewData[“UniqueID”]

HomeController.cs

public class HomeController : Controller
    {
        public IRepository _myRepository { get; set; }

        public HomeController(IRepository myRepository)
        {
            _myRepository = myRepository;
        }

        public IActionResult Index()
        {
            string uniqueID = _myRepository.GetUniqueID();
            ViewData[“UniqueID”] = uniqueID;
            return View();
        }
    }

The following is an Index view code. The unique ID in ViewData [“UniqueID”] is shown here and a partial view named UniquePartialView has been added to the view.

Index.cshtml

@{
    Layout = null;
    ViewData[“Title”] = “ASP.NET Core Service Scope”;
}

<h4>ASP.NET Core Service Scope</h4>

The Unique Value: @ViewData[“UniqueID”]

<br />
<br />

<partial name=”UniquePartialView”>

Next is a partial view code. The service is injected using @Inject directive and the unique ID is shown.

UniquePartialView.cshtml

@inject IRepository repository

PartialView ID: @repository.GetUniqueID()

The following is an output of the singleton. The unique ID here is the same for the parent view and the child view. Also, if you access the same page in the new browser, it will show the same unique ID. Even if you refresh the page it does not change the unique ID.

AddSingleton


AddScoped

For Scoped, an instance will be created per client request. The following is a ConfigureServices in the Startup.cs. Here I have registered the AddScoped for the above example Paragraph

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IRepository, MyRepository>();
    services.AddControllersWithViews();
}

The following is an output of AddScoped.  The unique ID here is the same for the parent view and partial view. But the unique ID will change when you refresh the page. This means it will create a new instance for each request.

AddScoped

AddTransient

For Transient, the instance will be created for each request.  To test AddTransient’s lifetime, I have registered the AddTransient in ConfigureServices method in Startup.cs.

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IRepository, MyRepository>();
    services.AddControllersWithViews();
}

The following is an output of AddTransient.  The unique ID here is different for the parent view and partial view. When refreshing the page, it brings up different unique IDs for parent and child view.

AddTransient

This blog explains what is the lifetime for the service and the difference between AddSingleton, AddScoped and AddTransient.

If you have any questions, please leave a comment below.

Categories
ASP.NET Core

Service Injection into View in ASP.NET Core

This blog is about how dependency is injected directly into view. Let us look at it using a small example.

The following is a ColorListService class that returns a list of strings.

Note

Put all your services in a separate folder called Services. So this will help you maintain a project structure

ColorListService.cs

public class ColorListService
{
    public List<string> GetColors()
    {
        return new List<string>() { “Red”, “Blue”, “Green”, “Yellow”, “Violet” };
    }
}

Before you can use a service, you must register for the service. See ASP.NET Service Scope for more information

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<ColorListService>();
    services.AddControllersWithViews();
}

The following is a view code. Here the ColorListService is injected using @Inject Directive. Finally a list of colors is listed using foreach.

ServiceDemo.cshtml

@{
    Layout = null;
    ViewData[“Title”] = “Service Injection into View”;
}

@inject SampleMVCApplication.Services.ColorListService  colors

<h4>Service Injection into View in ASP.NET Core</h4>

@foreach (string item in colors.GetColors())
{
    <div>@item</div>
}

Below is a HomeController code. It has a ServiceDemo() action which will render a ServiceDemo view.

HomeController.cs

public class HomeController : Controller
{
    public IActionResult ServiceDemo()
    {
         return View();
    }
}

The following is the output of the above code

Service Injection into View

This blog explains how to inject the service directly into the view with a small example.

If you have any questions, please leave a comment below.

Categories
ASP.NET Core

Group DropDownList Options in ASP.NET Core

This blog explains how to group options in a DropDownList in ASP.NET Core. Let’s look at it with an example.

This example is going to bind the list of movie names grouped by the release year with the Selected Tag Helper.

The following is the MyViewModelSample class. It has two properties, SelectedMovieID and MoviesList. The SelectedMovieID property will have the selected value of the drop-down list. The MoviesListproperty is what sets up a list of movies.

MyViewModelSample.cs

using Microsoft.AspNetCore.Mvc.Rendering;
public class MyViewModelSample
{
    public int SelectedMovieID { get; set; }
    public List<SelectListItem> MoviesList { get; set; }
}

The following is a controller code. This controller has 2 action methods, Sample() and SampleSubmit(). In the Sample() action method, values are assigned and passed to the view. In SampleSubmit() action method, the selected movie ID is retrieved from the view and passed to another view to be displayed on the page.

HomeController.cs

using Microsoft.AspNetCore.Mvc.Rendering;
public IActionResult Sample()
{
        var vm = new MyViewModelSample();

        var group2018 = new SelectListGroup { Name = “2018” };
        var group2019 = new SelectListGroup { Name = “2019” };

        var movieList = new List<SelectListItem>()
        {
            new SelectListItem() { Value = “1”, Text = “Incredibles 2”, Group = group2018 },
            new SelectListItem() { Value = “2”, Text = “Ralph Breaks the Internet”, Group = group2018 },
            new SelectListItem() { Value = “3”, Text = “Aladdin”, Group = group2019 },
            new SelectListItem() { Value = “4”, Text = “The Lion King”, Group = group2019 },
            new SelectListItem() { Value = “5”, Text = “Frozen II”, Group = group2019 }
        };
        vm.MoviesList = movieList;
        return View(vm);
}

[HttpPost]
public IActionResult SampleSubmit(MyViewModelSample vm)
{
    return View(“SampleResult”, vm.SelectedMovieID);
}

The following is a sample view. @Model.MoviesList is assigned to asp-items to bind a list of movie names. The SelectedMovieID property is assigned to the asp-for, thus providing the selected result.

Sample.cshtml

@{
    Layout = null;
}

@model MyViewModelSample

 <h4>Group DropDownList Options in ASP.NET Core</h4>

<form asp-controller=”Home” asp-action=”SampleSubmit” method=”post”>
      <select asp-items=”@Model.MoviesList” asp-for=”SelectedMovieID”></select>
      <input type=”submit” value=”submit” />
</form>

Below is a result view. The selected move ID will be displayed here.

SampleResult.cshtml

@{
    Layout = null;
}

@model int

<h4>Group DropDownList Options in ASP.NET Core</h4>
<div> The selected movie ID: @Model</div>

The following image is the output of the code above. Here you can see the names of the movies grouped by the movie release year. When the page is submitted it returns the selected movie ID.

Group DropDownList Options

If you have any questions, please leave a comment below.