2014-10-28 119 views
0

我想將值傳遞給我的控制器並執行查詢。然後,我想將查詢中的值返回給我的jquery函數,然後我可以將這些值分配給各種文本框。我無法弄清楚如何將數據返回給jquery。我只做了一個已經返回部分視圖的ajax調用。我正在ASP.NET中工作AJAX向控制器發送值並返回查詢結果

+0

你有什麼代碼嗎? – Ragnar 2014-10-28 13:58:09

回答

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. 
*/ 

然後你成功的Ajax功能將準備接受這個JSON結果:

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

這裏假設你正在使用jQuery。其他框架有不同的客戶端語法。使用jQuery來做Ajax比自己編寫代碼要好得多。

jQuery通常可以計算出您是否發回json或html,但如果您得到奇怪的結果,您可能需要將$ .post替換爲$ .ajax,並指定您期待json作爲回報。

2

您可以使用Ajax調用的函數裏面像下面,你可以打電話,只要你需要這個功能..

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

    } 

希望這將幫助你..