2014-10-28 3 views
0

컨트롤러에 값을 전달하고 쿼리를 실행하고 싶습니다. 그런 다음이 값을 다양한 텍스트 상자에 할당 할 수 있도록 쿼리의 값을 jquery 함수에 반환하고 싶습니다. 데이터를 jquery로 다시 가져 오는 방법을 알 수 없습니다. 나는 ajax 호출 만 수행하여 부분 뷰를 반환했습니다. ASP.NET에서 일하고 있습니다.AJAX가 컨트롤러에 값을 보내고 쿼리 결과를 반환합니다.

+0

코드가 있습니까? – Ragnar

답변

0

가장 좋은 방법은 Json을 사용하는 것입니다.

는 C#을 모델 서버 측 만들기 :

var result = new ResultModel 
       { 
        Item1 = "This is a result", 
        Item2 = "Another thing to return", 
        Item3 = 5, 
        ItemArray = new List<string>{ "Thing 1", "Thing 2" } 
       }; 

return Json(result); 

/* Server-side you don't *have* to use a model; an anonymous object is also fine, eg: 
* return Json(new { Item1 = "This is a result" }); etc. 
*/ 

다음 아약스 성공 기능이 JSON 결과를 받아 들일 준비가 될 것입니다 :

$.post(url, data, function(json) { 
     $("#textBox1").val(json.Item1); 
     $("#textBox2").val(json.Item2); 
     // etc.... 
}; 

이것은 당신이 jQuery를 사용하고있는 가정을. 다른 프레임 워크에는 다른 클라이언트 측 구문이 있습니다. jquery와 같은 것을 사용하여 Ajax를 작성하는 것은 직접 코딩하는 것보다 훨씬 더 멋지다.

jQuery는 보통 json이나 html을 보내고 있는지 여부를 판단 할 수 있지만 이상한 결과가 나면 $ .ajax를 $ .ajax로 대체하고 json을 반환 할 필요가 있음을 지정해야합니다.

당신은 아래와 같은 함수 내에서 아약스 전화를 사용할 수 있습니다
2

, 당신은 당신이 필요로 할 때마다이 함수를 호출 할 수 있습니다 ..

   function(id){ 
        $.ajax({ 
           url: "Your Controller/Method path", 
           data: JSON.stringify({ 
            id: id 
           }), 
           dataType: "json", 
           type: "POST", 
           async: false, 
           contentType: "application/json; charset=utf-8", 
           success: function (data) { 
           if(data.success){ 
          //Here you will get the value from the Controller if successfully executed 
          // you get values from data and you can assign those values to the textboxes based on your requirement..    
           } 
          } 
          }) 
         } 

컨트롤러 방법 :이 당신을 도울 것입니다

 public JsonResult functionName(int id) 
     { 
      JsonResult result = null; 

      try 
      { 
       var queryValue; 
       //here you can put your query and assign it to queryValue and return it back to the UI. 
       result = Json(new { success = true, data = queryValue }, JsonRequestBehavior.AllowGet); 
      } 
      catch (Exception ex) 
      { 
       result = Json(new { success = false, message = ex.Message }, JsonRequestBehavior.AllowGet); 
      } 
     return result; 
     } 

    } 

희망 ..

관련 문제