There is a button on the view

bool isPayAvailable = GetPaymentButtonEnabled(int statusId); <button id="payButton" @(!isPayAvailable ? "disabled" : string.Empty)>Оплатить</button> 

There is also a button that changes the statusId parameter. It turns out that in the handler for clicking this button there is a code that changes the attribute for the button "Pay". It turns out that there is duplication of code. The question then is: how to call a controller method from a JS file?

  • one
    @(!isPayAvailable ? "disabled" : string.Empty) - this is the same code that sets the on / off state. or I didn't understand the question - Bald
  • look in the code of this button for the attribute disabled and remove it. then the button will always be available. or else the @(... code is responsible for this @(... , which, judging by everything, checks for the presence of isPayAvailable and adds the disabled attribute to the button in the absence of the required data - lexxl
  • @Bald It is set, but after pressing another button it is reset. Now I'm trying to find in the code maybe there are still places where the attribute changes - Aleksandr Zharinov

1 answer 1

I would create a data attribute in it, write the required url , and in javascript got the value from this attribute and performed the necessary actions.


For example:

 <button id="customButton" data-target="@Url.Action("Метод", "Контроллер")" data-target="#content"></button> //здесь будет выведен результат запроса <div id="content"></div> 

Method in controller

 public ActionResult Test(string payId) { //код метода } 

somewhere in js

 $('customBtn').on('click', function(){ var target = $(this).data('target'); var url = $(this).data('url'); var payId = $("#payId").val(). var completeUrl = //склеиваем в итоге может получиться что то типа //TestController/Test?payId=5; $.ajax({ url: completeUrl, success: function (result) { $(target).html(result); } }) }); //дальнейшие действия }); 
  • I understand correctly that in this case the result of the controller method will lie in the url variable? How can I pass parameters to the method? - Aleksandr Zharinov
  • @AleksandrZharinov specify which parameter you want to transfer to the method, and how it is received - Bald
  • parameter, let's say, some Guid. As I see, the code actively uses a construction like @ Html.Hidden ("payId", payId). And then in JS: var payId = $ ("# payId"). Val (). How to transfer such a variable to a controller method? - Aleksandr Zharinov
  • @Html.Hidden("payId", payId) like its overloaded version of HiddenFor() intended to create a field invisible to the user, in this case the record id written there - Bald
  • Yes, I understood it, thanks. - Aleksandr Zharinov