2

What I want is, I want to check whether there is a file in the database or not. To do this I have a method in the controller which checks this and returns a boolean for the corresponding case. It looks like this:

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

I simply just check if there is any file assigned to the given employee.

Now I would like to call this method from my javascript in the view, and get the return value, so that I can let the user know, if there is a file assigned to the selected employee or not. It may look like this:

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

So my question now is, how do I get the get the return value from the method in the controller?

4 Answers 4

2

I would suggest few changes here:

Change your controller method to have return type ActionResult or JsonResult and I prefer JsonResult would be enough here and retrun Json response from controller and manipulate this method with $.get. You also need to change parameter to string because the parameter will be received as 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);
         }
    }
}  

Now your ajax-get call would be as below:

$("#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.");
       }
   })
});  
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the response! It seems like a good solution. However, I am confused about the 'response'-parameter - what is it, and is it the "real" parameter or is it to be substituted with somehting? :)
Nope.. Keep it as it is.. Its just a reference to server response.. :) You can give name of your own.. :)
0

You need to set-up a single page script using your ASP fileInDb function and then communicate with that page using AJAX from the browser. If you're unfamiliar with AJAX I'd recommend using the jQuery implementation to get you started.

Comments

0

You can use jquery and ajax to achieve this. Call your method using an ajax call from your client code. Here is an example as a reference :Calling controller method from view

Comments

0

In the backend create a method to call, returning a JsonResult

    public JsonResult fileInDb(int empId)
    {
         // your code - set fileExists to true/false

        JsonResult returnObj = new JsonResult
        {
            Data = new
            {
                FileExists = fileExists ;
            }
        };

        return Json(returnObj);
    }

in your javascript code use $.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);
            }
        });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.