我想要的是,我想检查数据库中是否有文件。为此,我在 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
类型为ActionResult
或JsonResult
,我更喜欢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.");
}
})
});
关于javascript - 获取Controller的返回值给javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33915454/