locked
How to select an element by id or class RRS feed

  • Question

  • User887623398 posted

    Hello,

    How to select an element by id or class in Blazor?

    Is this posible?

    like jquery:

    $( ".myClass" )

    thanks,

    Saeed

    Wednesday, July 29, 2020 9:36 AM

Answers

  • User475983607 posted

    SaeedP

    Please consider this component:

    <RadzenUpload @ref="upload" Auto="false" Url="upload/single" Style="margin-bottom: 20px;"
                          Progress="@((args) => OnProgress(args, "Manual Upload"))" />

    How can I access the Url atribute?

    Can I use @ref?

    Come on man!  You did not include any code or explain what you're trying to do?!  My best guess is you are trying to create a component reference???  

    Child Component

    @page  "/RadzenUpload"
    <h3>RadzenUpload</h3>
    
    <div @attributes="AdditionalAttributes">Hello</div>
    
    @code {
    
        [Parameter(CaptureUnmatchedValues = true)]
        public IDictionary<string, object> AdditionalAttributes { get; set; }
    
        public string DoSomething()
        {
            return AdditionalAttributes["Url"].ToString();
        }
    }

    Parent

    @page "/RadzenUploadParent"
    
        <RadzenUpload @ref="upload"  Url="upload/single" />
        <button class="btn btn-primary" @onclick="DoSomething">Click me</button>
    
    @code {
        private RadzenUpload upload;
    
        private void DoSomething()
        {
            Console.WriteLine(upload.DoSomething());
            return;
        }
        
    
    }

    Click the button and "upload/single" is written to the browser console.

    Edit Or...

    @page  "/RadzenUpload"
    <h3>RadzenUpload</h3>
    
    <div @attributes="AdditionalAttributes">Hello</div>
    
    @code {
    
        [Parameter(CaptureUnmatchedValues = true)]
        public IDictionary<string, object> AdditionalAttributes { get; set; }
    
        public IDictionary<string, object> GetAttributes()
        {
            return AdditionalAttributes;
        }
    }
    @page "/RadzenUploadParent"
    
        <RadzenUpload @ref="upload"  Url="upload/single" />
        <button class="btn btn-primary" @onclick="DoSomething">Click me</button>
    
    @code {
        private RadzenUpload upload;
    
        private void DoSomething()
        {
            IDictionary<string, object> attributes =  upload.GetAttributes();
            Console.WriteLine(attributes["Url"].ToString());
            return;
        }
    
    
    }
    

    Reference doc.

    https://docs.microsoft.com/en-us/aspnet/core/blazor/components/?view=aspnetcore-3.1#capture-references-to-components

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, July 29, 2020 5:25 PM

All replies

  • User475983607 posted

    Hello,

    How to select an element by id or class in Blazor?

    Is this posible?

    like jquery:

    $( ".myClass" )

    thanks,

    Saeed

    Saeedp, You really need to take the time to READ the official documentation!  Blazor uses JavaScript interop to talk to JavaScript/jQuery. 

    https://docs.microsoft.com/en-us/aspnet/core/blazor/call-javascript-from-dotnet?view=aspnetcore-3.1

    Secondly, you did not share any Blazor code or explain the actual problem you are trying to solve.  Since Blazor is a client side application and access to an element is very simple, it is not clear why you need jQuery.  

    Wednesday, July 29, 2020 1:11 PM
  • User-474980206 posted

    As blazor is server side or WASM it can not directly access the DOM, thus selecting a DOM node makes no sense. 

    in blazor you build a component tree, from which DOM updates are generated. A component should have the compete rendering logic. If you need to update DOM directly (advanced)  then you use JavaScript interop. 

    the blazor routing, event and DOM processing is all written in JavaScript. Blazor is just the component html render logic and state management.

    Wednesday, July 29, 2020 2:57 PM
  • User887623398 posted

    bruce (sqlwork.com)

    As blazor is server side or WASM it can not directly access the DOM, thus selecting a DOM node makes no sense. 

    in blazor you build a component tree, from which DOM updates are generated. A component should have the compete rendering logic. If you need to update DOM directly (advanced)  then you use JavaScript interop. 

    the blazor routing, event and DOM processing is all written in JavaScript. Blazor is just the component html render logic and state management.

    Please consider this component:

    <RadzenUpload @ref="upload" Auto="false" Url="upload/single" Style="margin-bottom: 20px;"
                          Progress="@((args) => OnProgress(args, "Manual Upload"))" />

    How can I  dynamically access the Url atribute? I want to save it in a variable.

    Can I use @ref?

    Wednesday, July 29, 2020 4:36 PM
  • User475983607 posted

    SaeedP

    Please consider this component:

    <RadzenUpload @ref="upload" Auto="false" Url="upload/single" Style="margin-bottom: 20px;"
                          Progress="@((args) => OnProgress(args, "Manual Upload"))" />

    How can I access the Url atribute?

    Can I use @ref?

    Come on man!  You did not include any code or explain what you're trying to do?!  My best guess is you are trying to create a component reference???  

    Child Component

    @page  "/RadzenUpload"
    <h3>RadzenUpload</h3>
    
    <div @attributes="AdditionalAttributes">Hello</div>
    
    @code {
    
        [Parameter(CaptureUnmatchedValues = true)]
        public IDictionary<string, object> AdditionalAttributes { get; set; }
    
        public string DoSomething()
        {
            return AdditionalAttributes["Url"].ToString();
        }
    }

    Parent

    @page "/RadzenUploadParent"
    
        <RadzenUpload @ref="upload"  Url="upload/single" />
        <button class="btn btn-primary" @onclick="DoSomething">Click me</button>
    
    @code {
        private RadzenUpload upload;
    
        private void DoSomething()
        {
            Console.WriteLine(upload.DoSomething());
            return;
        }
        
    
    }

    Click the button and "upload/single" is written to the browser console.

    Edit Or...

    @page  "/RadzenUpload"
    <h3>RadzenUpload</h3>
    
    <div @attributes="AdditionalAttributes">Hello</div>
    
    @code {
    
        [Parameter(CaptureUnmatchedValues = true)]
        public IDictionary<string, object> AdditionalAttributes { get; set; }
    
        public IDictionary<string, object> GetAttributes()
        {
            return AdditionalAttributes;
        }
    }
    @page "/RadzenUploadParent"
    
        <RadzenUpload @ref="upload"  Url="upload/single" />
        <button class="btn btn-primary" @onclick="DoSomething">Click me</button>
    
    @code {
        private RadzenUpload upload;
    
        private void DoSomething()
        {
            IDictionary<string, object> attributes =  upload.GetAttributes();
            Console.WriteLine(attributes["Url"].ToString());
            return;
        }
    
    
    }
    

    Reference doc.

    https://docs.microsoft.com/en-us/aspnet/core/blazor/components/?view=aspnetcore-3.1#capture-references-to-components

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, July 29, 2020 5:25 PM
  • User-474980206 posted

    <RadzenUpload @ref="upload" Auto="false" Url="upload/single" Style="margin-bottom: 20px;"
                          Progress="@((args) => OnProgress(args, "Manual Upload"))" />

    How can I  dynamically access the Url atribute? I want to save it in a variable.

    Can I use @ref?

    why wouldn't it be a configuration/state variable to begin with?

    Wednesday, July 29, 2020 7:53 PM
  • User887623398 posted

    bruce, I can't exactly understand what you mean.

    By I need dynamicaly access the UrI and save it in a variable to use it for sending an image to instagram.

    You can see the class below :

    internal class UploadPhoto : IDemoSample
        {
            private readonly IInstaApi _instaApi;
    
            public UploadPhoto(IInstaApi instaApi)
            {
                _instaApi = instaApi;
            }
    
            public async Task DoShow()
            {
                var mediaImage = new InstaImage
                {
                    Height = 1080,
                    Width = 1080,
                    URI = new Uri(Path.GetFullPath(@"c:\someawesomepicture.jpg"), UriKind.Absolute).LocalPath
                };
                var result = await _instaApi.UploadPhotoAsync(mediaImage, "someawesomepicture");
                Console.WriteLine(result.Succeeded
                    ? $"Media created: {result.Value.Pk}, {result.Value.Caption}"
                    : $"Unable to upload photo: {result.Info.Message}");
            }
        }

    Please if my way is not correct or there are other ways, let me know.

    Thursday, July 30, 2020 3:00 PM
  • User475983607 posted

    The code I shared above fetches the URL attribute dynamically.  Seems you have another issue?

    Thursday, July 30, 2020 3:35 PM
  • User887623398 posted

    The code I shared above fetches the URL attribute dynamically.  Seems you have another issue?

    Yes, you are right. And thanks for the code.

    Just curious if there are other ways.

    Thursday, July 30, 2020 3:53 PM
  • User475983607 posted

    Yes, you are right. And thanks for the code.

    Just curious if there are other ways.

    Other ways to do what exactly?  The code sample is totally dynamic.  There can be one or many attributes that can vary by name and value.  What else are you looking for?

    Thursday, July 30, 2020 4:08 PM
  • User887623398 posted

    Other ways to do what exactly?  The code sample is totally dynamic.  There can be one or many attributes that can vary by name and value.  What else are you looking for?

    I expected it to have a have a way like ASP.net webform or javascript or jquery.

    I mean after declaring the component id or class could access the component attribute.

    Thursday, July 30, 2020 8:18 PM
  • User475983607 posted

    SaeedP

    I expected it to have a have a way like ASP.net webform or javascript or jquery.

    I mean after declaring the component id or class could access the component attribute.

    In Blazor, the component attributes are accessed from the component instance as shown in the sample code above.  There is no reason to query the DOM to get the component like jQuery or JavaScript.  Blazor is a different technology and you really should take the time to read the fundamentals docs if you are interested in learning Blazor.  

    Thursday, July 30, 2020 8:37 PM
  • User-474980206 posted

    while accessing a child's properties is valid in some cases, in general it is code smell. the child component does not even exist until after parent render (so you need to careful when you read them). Parents should be setting its childs parameters, not reading them. 

    you should not be walking the component tree to access values. any value your component needs should be passed as a parameter or in state. blazor supports cascading values if a  nested child needs a value from up the tree:

       https://docs.microsoft.com/en-us/aspnet/core/blazor/components/cascading-values-and-parameters?view=aspnetcore-3.1

     the parent can pass a callback to a child to receive a parameter determined by the child, typically in response to an event in the child.  

    understanding component parameter state (not to be confused with persistent state like session storage) is key to understanding blazor components. currently blazor uses what's often called local state (the state is owned by the component, but maintained outside the component) . cascading values is its version of global state.  

    while a component can calculate parameters for its children during render. a component should not modify its own parameters except during an event. your components job is to render state. async events are used to update state.

    so if the url of a link is required in another component, it should be refactored to a binding/parameter variable used by both. 

     

    Friday, July 31, 2020 9:15 PM