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

蓝咒 提交于 2021-01-28 09:15:30

问题


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?


回答1:


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();
        })
    })
    


来源:https://stackoverflow.com/questions/48937147/how-to-set-value-in-net-tag-helper-attribute-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!