Skip to content
Advertisement

Blazor : Change image src with @Onclick without js

i’m begin to learn c# after years of Delphi. I decide to learn about blazor. i’m trying to program about basic card mind game. There must be random images on page and on init page all images with black picture (0.jpg) I am creating randomized image’s id property with for loop at top of the xxx.razor

For example

<image src=0.jpg id=1>
<image src=0.jpg id=3>
<image src=0.jpg id=1>
<image src=0.jpg id=2>
<image src=0.jpg id=2>
<image src=0.jpg id=3>

When the user click on id=3 image image property should be so on that img 3.jpg will be shown.

i made that scenerio with jsInterop its basic. But i want to know can i do that with only c# code? Tnks. Programming enviroment : Linux mint & Visual Studio Code & .Net Core 3.1

Advertisement

Answer

The problem here is you need to be thinking about components and not directly writing to each element. What you should do is create an object that represents the state of the component, in your case a card with a Hidden/Shown state, a FileName, and the Src value.

Below I’ll call this state Image and represent it with a class.

    public class Image
    {
        public int FileName {get;set;}
        public bool Shown {get;set;}
        public string Src => Shown ? $"{FileName}.jpg" : "0.jpg";
    }

Next, we need to create a collection of items. This could be static, come from a data source like a database, etc. In this example I’ll use the Enumerable.Range function to generate a list of values ranging from 1-10. The Select method will assign those values to a new Image setting the FileName value. The values are stashed in a list.

List<Image> items = Enumerable.Range(1, 10).Select(i => new Image { FileName = i}).ToList();

In the UI portion, we need to render some markup. An image would work fine here, but a button was easier for example purposes. In the onclick event, we simply set the Shown value to true. Setting this value updates the Src property displaying the “shown” image, 1-10.jpg.

@foreach (var item in items) {
    <button @onclick="@(()=> item.Shown = true)">@item.Src</button>
}

Putting it all together you have:

@foreach (var item in items) {
    <button @onclick="@(()=> item.Shown = true)">@item.Src</button>
}

@code {
    List<Image> items = Enumerable.Range(1, 10).Select(i => new Image { FileName = i}).ToList();

    public class Image
    {
        public int FileName {get;set;}
        public bool Shown {get;set;}
        public string Src => Shown ? $"{FileName}.jpg" : "0.jpg";
    }
}

You can replace the button with an image for your task.

<img src="@item.Src" @onclick="@(()=> item.Shown = true)" />

See the solution working live here https://blazorfiddle.com/s/m01smajj

If you want to toggle Shown on/off

@foreach (var item in items) {
    <button @onclick="@(()=> item.Shown = !item.Shown)">@item.Src</button>
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement