获取Controller到javascript的返回值

Get return value from Controller to javascript

本文关键字:返回值 javascript Controller 获取      更新时间:2023-09-26

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

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.");
        }
    });  

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

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

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.");
       }
   })
});  

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

您可以使用jquery和ajax来实现这一点。使用客户端代码中的ajax调用来调用方法。以下是一个示例作为参考:从视图调用控制器方法

在后端创建一个要调用的方法,返回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);
            }
        });