2014-02-18 2 views
2

저는 클라이언트 - 서버 프로그래밍 개념에 익숙하지 않습니다. MVC 3 컨트롤러 동작에 4 개의 jars를 보내려면 무엇이 필요합니다.mvc 컨트롤러에 js 변수를 보내는 방법

$(document).ready(function() { 
     var $jcrop; 

     $('#image').Jcrop({ 
      bgColor: 'red', 
      onSelect: refreshData 
     }, function() { 
      $jcrop = this; 
     }); 

     function refreshData(selected) { 
      myData = { 
       x1: selected.x1, 
       x2: selected.x2, 
       y1: selected.y1, 
       y2: selected.y2 
      }; 
     } 
    }); 

브라우저에서 내 배너를 가져옵니다.

서버 측에서 내가 가지고 있습니다 : 내 행동에 JS에서 내 네 PARAMS를 게시 할 수있는 쉬운 방법은

public ActionResult CreateCover(ImageCoordinates coordinates) { 
     ViewData.Model = coordinates; 
     return View(); 
    } 

public class ImageCoordinates 
{ 
    public int x1 { get; set; } 
    public int x2 { get; set; } 
    public int y1 { get; set; } 
    public int y2 { get; set; } 
} 

있습니까? 나는이

 $.ajax({ 
      url: '/dashboard/createcover', 
      type: 'POST', 
      data: JSON.stringify(myData), 
      contentType: 'application/json; charset=utf-8', 
      success: function (data) { 
       alert(data.success); 
      }, 
      error: function() { 
       alert("error"); 
      }, 
      async: false 
     }); 

처럼 $ 아약스

를 사용하고 있으며,이 사이트에서 몇 가지 예제를 사용하려고하지만,이 일을하지 않고, 난 내 행동에 0 0 0 0을 받았다. 그러나 솔직히이 jquery 함수를 호출하는 방법을 모르겠다. 단추를 클릭하여 호출해야합니까, 아니면 양식을 게시 할 때 자동 호출입니까? 그리고이 매개 변수를 전송하는 다른 방법이 있습니까? 컨트롤러에 전달 된 객체의 이름을 변경

답변

10

는 솔루션 간다 -

모델 -

public class ImageCoordinates 
{ 
    public int x1 { get; set; } 
    public int x2 { get; set; } 
    public int y1 { get; set; } 
    public int y2 { get; set; } 
} 

액션 -

public ActionResult CreateCover(ImageCoordinates coordinates) 
    { 
     return null; 
    } 

는 작업에 AJAX 호출을하는보기를 만들 수 있습니다.

<script src="~/Scripts/jquery-1.10.2.min.js"></script> 

<script> 
    function submitForm() { 

     var model = new Object(); 
     model.x1 = 120; 
     model.y1 = 240; 
     model.x2 = 360; 
     model.y2 = 480; 


     jQuery.ajax({ 
      type: "POST", 
      url: "@Url.Action("CreateCover")", 
      dataType: "json", 
      contentType: "application/json; charset=utf-8", 
      data: JSON.stringify({ coordinates: model }), 
      success: function (data) { 
       alert(data); 
      }, 
      failure: function (errMsg) { 
       alert(errMsg); 
      } 
     }); 
    } 
</script> 

<input type="button" value="Click" onclick="submitForm()" /> 

는 출력 -

enter image description here

+1

"데이터 : JSON.stringify ({좌표 : 모델})"가장 중요한 부분을 강조 표시합니다. –

+0

감사합니다. 테스트 해 보았고 컨트롤러 작업에서 변수를 수신했습니다. 추가 질문은받는 ​​매개 변수로 다른 뷰를 렌더링하는 방법입니다. – CadmusX

+0

public ActionResult CreateCover (ImageCoordinates 좌표) { ViewData.Model = 좌표; 돌아 가기 View(); }이 코드는 내 코드이지만, 여전히 그 페이지에서 내 매개 변수를 보냈습니다. 디버그에서보기 내 렌더링 작업을 수행 할,보기를 렌더링하지 않습니다. – CadmusX

2

시도 :

$.ajax({ 
    url: '/dashboard/createcover', 
    type: 'POST', 
    data: {coordinates : JSON.stringify(myData)}, //change here 
    contentType: 'application/json; charset=utf-8', 
    success: function (data) { 
     alert(data.success); 
    }, 
    error: function() { 
     alert("error"); 
    }, 
    async: false 
}); 

이는 JSON 객체로 값을 게시 할 예정입니다 있습니다. 당신과 같이 컨트롤러를 수정해야합니다

public ActionResult CreateCover(string jsonCoordinates) { 
    ImageCoordinates coordinates = JsonConvert.DeserializeObject<ImageCoordinates >(jsonCoordinates); 

    ViewData.Model = coordinates; 
    return View(); 
} 

당신은 또한 Newtonsoft.Json에 대한 참조를 추가해야합니다. 여기

+0

아니 .. MVC는 –

+0

@AlexanderTaran 역 직렬화 할 필요 바인더 JSON 모델에 내장되어있어, 나는 부분적으로 동의합니다. 사전을 전달하면서 조금 놀면 파싱의 일부가 컨트롤러에서 명시 적으로 수행되어야한다는 결론에 빨리 도달합니다. –

+0

@AndreiV 먼저 도움과 시간을 가져 주셔서 감사합니다. 나는 당신의 코드를 사용하려했지만, 500 명의 오류가 발생했다. – CadmusX

관련 문제