AJAX向控制器发送值并返回查询结果

时间:2014-10-28 13:53:21

标签: jquery asp.net ajax asp.net-mvc

我想将值传递给控制器​​并执行查询。然后我想将查询中的值返回到我的jquery函数,然后我可以将这些值分配给各种文本框。我无法弄清楚如何将数据恢复到jquery。我只做过ajax调用,返回部分视图。我在ASP.NET中工作

2 个答案:

答案 0 :(得分: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;
      }

   }

希望这会对你有帮助..

答案 1 :(得分: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作为回报。

相关问题