Search code examples
javascriptc#jqueryasp.net-core-tag-helpers

How to set value in .net tag helper attribute using javascript?


I am trying to set parameter value read from a textbox on the page to this link:

<a asp-action="RetrieveEmailRecipients" asp-route-clientnumber="getClientNumber()">Retrieve Email Recipients</a>

And I have Javascript down somewhere else at the bottom of the page. But appreatly this is not the right way to pass value to MVC action method's parameter.

What parameter ClientNumber read in action is whatever the string/value in asp-route-clientnumber, in this case the value is getClientNumber().

What is the correct way to set value in the attribute using javascript/jquery?


Solution

  • you are mixing server side code and client side code together

    I am assuming your getClientNumber() is a javascript function

    Tag Helper is generated before javascript comes in, so when server is generating the html, it has no knowledge of what getClientNumber() is so will treated as literal string

    So the proper way of doing it will be modify the url with jquery when client number available

    Something like:

    1. give the anchor an identifier - so you can access it using jquery easily and remove the route

      <a id="aRetriveEmail" asp-action="RetrieveEmailRecipients">Retrieve Email Recipients</a>
      
    2. modify the attribute of the anchor to include your clientNumber whenever you have clientNumber ready, or use javascript to navigate to it

      $(function(){
          $("#aRetriveEmail").click(function(){
              // example of how modifying href when client number ready
              // $(this).attr("href", $(this).attr("href") + "?clientnumber=" + getClientNumber());
      
              // or navigate to the url
              location.href = $(this).attr("href") + "?clientnumber=" + getClientNumber();
          })
      })