Search code examples
c#asp.net-corerazor-pages

Asp.Net Core Razor Pages: asp-route to use value from input on same page


From an Index page, is it possible to get the text value from an input like this:

<input id="inpSearchMembers" class="form-control small-text" placeholder="Search for a Member..." />

and feed it into the asp-route-searchText attribute value in something like this:

<a id="btnSearchMembers" class="btn btn-outline-primary small-text" asp-page="/Search" asp-route-searchText="~Value from InpSearchMember~" >Search</a>

So that the attribute asp-route-searchText contains the text of the input field id="inpSearchMembers" before sending back to the code-behind when clicked?


Solution

  • the asp-route-... will be used by the AnchorTagHelper to render the attribute href once and statically without any magic binding like what you wish for. So for example, if you have a route pattern like /abc/{searchText}. After being rendered to HTML, the A element will have its href rendered like /abc/whatever-from-asp-route-searchText. I would not try to send value via route data in such use cases if possible. But if you have to, you need to use javascript here to replace the searchText (initially rendered as a unique token inside the href) with the dynamic value from the other input before the link is visited by clicking.

    First you prepare the code in the razor view like this:

    @{
       var searchToken = Guid.NewGuid().ToString();
    }
    <a id="btnSearchMembers" class="btn btn-outline-primary small-text" 
       asp-page="/Search" asp-route-searchText="@searchToken">Search</a>
    

    Next, you write code for the javascript part to replace the search token with runtime (dynamic) value from the other input:

    window.onload = function(){
        var searchLink = document.getElementById("btnSearchMembers");
        var originalHref = searchLink.href;
        searchLink.onclick = function(e){
           //get the value from the other input and replace the link's href 
           //before it's visited by the link click.
           var searchTextElement = document.getElementById("inpSearchMembers");
           e.target.href = originalHref.replace("@searchToken", searchTextElement.value);  
        };
    }
    

    Of course the above javascript code should be written in the same razor view file so that you can access to the server variable searchToken.