【问题标题】:Get return value from Controller to javascript从Controller获取返回值到javascript
【发布时间】:2015-11-25 11:33:04
【问题描述】:

我想要的是,我想检查数据库中是否有文件。为此,我在控制器中有一个方法,它检查这个并为相应的情况返回一个布尔值。它看起来像这样:

public bool fileInDb(int empId)
    {
        using (SLADbContext db = new SLADbContext())
        {
            bool file = db.CompetenceUploads.Any(x => x.EmployeeId == empId);
            if (file)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }  

我只是检查是否有任何文件分配给给定的员工。

现在我想在视图中从我的 javascript 调用此方法,并获取返回值,这样我就可以让用户知道是否有文件分配给所选员工。它可能看起来像这样:

$("#get-file").click(function() {

        empId: $("#EmployeeSelect").val();
        var fileInDb = // Get the return value from the method 'fileInDb'

        if(fileInDb) {
            // Let the user download the file he/she requested
            var url = "@Url.Action("GetUploadedFile", "Competence")";
            this.href = url + '?empId=' + encodeURIComponent($("#EmployeeSelect").val());
        } else {
            alert("There is no file assigned to this employee.");
        }
    });  

所以我现在的问题是,如何从控制器中的方法获取返回值?

【问题讨论】:

    标签: javascript c# asp.net .net


    【解决方案1】:

    我建议在这里进行一些更改:

    controller 方法更改为return 类型ActionResultJsonResult,我更喜欢JsonResult 在这里就足够了,然后从controller 返回Json 响应并使用 操作此方法$.get。您还需要将参数更改为string,因为parameter 将作为Json string 接收。

    public JsonResult fileInDb(string eId) //change signature to string and then convert to int 
    {
        int empId=Convert.ToInt32(eId);
        using (SLADbContext db = new SLADbContext())
        {
             bool file = db.CompetenceUploads.Any(x => x.EmployeeId == empId);
             if (file)
             {
                 return Json(new { result = true },JsonRequestBehavior.AllowGet);
             }
             else
             {
                 return Json(new { result = false},JsonRequestBehavior.AllowGet);
             }
        }
    }  
    

    现在您的ajax-get 电话如下:

    $("#get-file").click(function() {
       var eId= $("#EmployeeSelect").val();
       $.get('/YourControllerName/fileInDb',{'eId':eId},function(response){
           //you just need to get the response so $.get is enough to manipulate
           //this will be called once you get the response from controller, typically a callback
           if(response.result) //same result variable we are returning from controller.
           {
                // Let the user download the file he/she requested
                var url = "@Url.Action("GetUploadedFile", "Competence")";
                this.href = url + '?empId=' + encodeURIComponent($("#EmployeeSelect").val());
           } else {
                alert("There is no file assigned to this employee.");
           }
       })
    });  
    

    【讨论】:

    • 感谢您的回复!这似乎是一个很好的解决方案。但是,我对“响应”参数感到困惑-它是什么,它是“真实”参数还是要用某些东西代替? :)
    • 不.. 保持原样.. 它只是对服务器响应的引用.. :) 你可以给自己的名字.. :)
    【解决方案2】:

    您需要使用 ASP fileInDb 函数设置单页脚本,然后使用浏览器中的 AJAX 与该页面通信。如果您不熟悉 AJAX,我建议您使用 jQuery implementation 来帮助您入门。

    【讨论】:

      【解决方案3】:

      您可以使用 jquery 和 ajax 来实现这一点。使用来自您的客户端代码的 ajax 调用来调用您的方法。这是一个示例作为参考:Calling controller method from view

      【讨论】:

        【解决方案4】:

        在后端创建一个方法来调用,返回一个JsonResult

            public JsonResult fileInDb(int empId)
            {
                 // your code - set fileExists to true/false
        
                JsonResult returnObj = new JsonResult
                {
                    Data = new
                    {
                        FileExists = fileExists ;
                    }
                };
        
                return Json(returnObj);
            }
        

        在您的 javascript 代码中使用 $.ajax

               $.ajax({
                    cache: false,
                    url: '@Url.Action("fileInDb")',
                    data: { 'empId': someVar },
                    type: 'POST',
                    success: function (response) {
                          if (response.Data.FileExists === true) {
                            // do something
                          }   else {
                           // it was false
                          }
                        },
                    error: function (er) {
                        alert('Error!' + er);
                    }
                });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-03-13
          • 1970-01-01
          • 2016-01-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-03-13
          • 2021-11-20
          相关资源
          最近更新 更多