Search code examples
javascriptc#asp.net-mvcasp.net-core

asp-action and asp-controller in innerHtml in js file


I need insert Html in Html document. I use innerHtml for this.

let newCardHTML = `
                    <div class="header">
                        <h4 class="card-counter">${currentCardNumber}</h4>
                        a class="button-bin btn" asp-action="DeleteCard" asp-controller="Cards" asp-route-cardId="currentCardNumber" ></a>                       
                    </div>`

I receive error Attribute DeleteCard is not allowed here.

I try

var url = '@Url.Action("DeleteCard","Cards", new {cardId = 0})';
var linkHtml = '<a class = button-bin btn" href ="' + url+ '"></a>';
newCardHTML.querySelector('.header').innerHTML = linkHtml;

However this doesn't work and Local variable linkHtml is redundant.


Solution

  • You couldn't directly use the Razor syntax with the asp.net core tag helper inside the js string, one solution is using the @Url.Action to generate the url and then put it inside the js.

    More details, you could refer to below codes:

    <div class="container">
    
    
    </div>
    
    @{
        var baseUrl = Url.Action("DeleteCard", "Cards", new { cardId = 0 });
    }
    
    
    @section Scripts{
    
    
        <script>
             
    let currentCardNumber = 1; 
    
    // Replace the '0' in the base URL with the actual card number
    let deleteCardUrl = '@baseUrl'.replace('0', currentCardNumber);
    
    let newCardHTML = `
        <div class="header">
            <h4 class="card-counter">${currentCardNumber}</h4>
            <a class="button-bin btn" href="${deleteCardUrl}"></a>                       
        </div>
    `;
    
     
    document.querySelector('.container').innerHTML += newCardHTML;
            </script>
    }
    

    Result:

    enter image description here