developer tip

JavaScript에서 ASP.NET MVC 작업 메서드 호출

optionbox 2020. 12. 4. 08:08
반응형

JavaScript에서 ASP.NET MVC 작업 메서드 호출


다음과 같은 샘플 코드가 있습니다.

 <div class="cart">
      <a onclick="addToCart('@Model.productId');" class="button"><span>Add to Cart</span></a>
 </div>
 <div class="wishlist">
      <a onclick="addToWishList('@Model.productId');">Add to Wish List</a>
 </div>
 <div class="compare">
      <a onclick="addToCompare('@Model.productId');">Add to Compare</a>
 </div>    

컨트롤러 작업 메서드를 호출하는 JavaScript 코드를 어떻게 작성할 수 있습니까?


jQuery ajax 사용 :

function AddToCart(id)
{
   $.ajax({
      url: 'urlToController',
      data: { id: id }
   }).done(function() {
      alert('Added'); 
   });
}

http://api.jquery.com/jQuery.ajax/


아래와 같이 Javascript사용 하여 Action Method호출하기 만하면 됩니다.

var id = model.Id; //if you want to pass an Id parameter
window.location.href = '@Url.Action("Action", "Controller")/' + id;

도움이 되었기를 바랍니다...


addToCart 메소드를 호출하고 제품 ID를 전달합니다. 이제 jQuery ajax를 사용하여 해당 데이터를 서버 측 작업 메소드에 전달할 수 있습니다.

jQuery 게시물은 jQuery ajax의 짧은 버전입니다.

function addToCart(id)
{
  $.post('@Url.Action("Add","Cart")',{id:id } function(data) {
    //do whatever with the result.
  });
}

성공 콜백 및 오류 처리와 같은 더 많은 옵션을 원한다면 jQuery ajax를 사용하십시오.

function addToCart(id)
{
  $.ajax({
  url: '@Url.Action("Add","Cart")',
  data: { id: id },
  success: function(data){
    //call is successfully completed and we got result in data
  },
  error:function (xhr, ajaxOptions, thrownError){
                  //some errror, some show err msg to user and log the error  
                  alert(xhr.responseText);

                }    
  });
}

ajax 호출을 할 때 Url.Action작업 메서드에 대한 경로를 생성하는 것과 같은 Html 도우미 메서드를 사용하는 것이 좋습니다 .

This will work if your code is in a razor view because Url.Action will be executed by razor at server side and that c# expression will be replaced with the correct relative path. But if you are using your jQuery code in your external js file, You may consider the approach mentioned in this answer.


If you do not need much customization and seek for simpleness, you can do it with built-in way - AjaxExtensions.ActionLink method.

<div class="cart">
      @Ajax.ActionLink("Add To Cart", "AddToCart", new { productId = Model.productId }, new AjaxOptions() { HttpMethod = "Post" });
</div>

That MSDN link is must-read for all the possible overloads of this method and parameters of AjaxOptions class. Actually, you can use confirmation, change http method, set OnSuccess and OnFailure clients scripts and so on


If you want to call an action from your JavaScript, one way is to embed your JavaScript code, inside your view (.cshtml file for example), and then, use Razor, to create a URL of that action:

$(function(){
    $('#sampleDiv').click(function(){
        /*
         While this code is JavaScript, but because it's embedded inside
         a cshtml file, we can use Razor, and create the URL of the action

         Don't forget to add '' around the url because it has to become a     
         valid string in the final webpage
        */

        var url = '@Url.Action("ActionName", "Controller")';
    });
});

You can simply add this when you are using same controller to redirect

var url = "YourActionName?parameterName=" + parameterValue;
window.location.href = url;

Javascript Function

function AddToCart(id) {
 $.ajax({
   url: '@Url.Action("AddToCart", "ControllerName")',
   type: 'GET',
   dataType: 'json',
   cache: false,
   data: { 'id': id },
   success: function (results) {
        alert(results)
   },
   error: function () {
    alert('Error occured');
   }
   });
   }

Controller Method to call

[HttpGet]
  public JsonResult AddToCart(string id)
  {
    string newId = id;
     return Json(newId, JsonRequestBehavior.AllowGet);
  }

You can set up your element with

value="@model.productId"

and

onclick= addToWishList(this.value);

참고URL : https://stackoverflow.com/questions/8952953/calling-asp-net-mvc-action-methods-from-javascript

반응형