gpt4 book ai didi

javascript - 从 Controller 获取返回值到javascript

转载 作者:行者123 更新时间:2023-11-29 21:38:47 26 4
gpt4 key购买 nike

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

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

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

现在我想在 View 中从我的 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 中的方法获取返回值?

最佳答案

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

更改您的 controller方法return输入 ActionResultJsonResult我更喜欢JsonResult在这里就足够了,然后重新运行 Json来自 controller 的回复并使用 $.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.");
}
})
});

关于javascript - 从 Controller 获取返回值到javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33915454/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com