简体   繁体   中英

Ajax Call Success Now Working - Passing JSON Object [String]

I am trying to develop some validation within my application to check if a Function Name all ready exists within the database. Rather than using SQL I wanted to use ajax to pass this data through.

Unfortunately when trying to pass this JSON (String) Object , the response is never being passed success: function (response) and I am getting an error message.

I was hoping for some advise as to why this might be occurring as I believe my code is within the correct format to complete successfully.

I have tried changing the datatype to text and have also included contentType: 'application/json; charset=utf-8 contentType: 'application/json; charset=utf-8 but this has not helped solve the issue.

function AllowedFunction(FunctionName) {
    var result = "None";        
    $.ajax({
        url: '@Url.Action("FunAllowed")',
        type: "POST",            
        dataType: "JSON",
        data: { FunctionName: FunctionName },
        success: function (response) {
            if (response.length > 0)
            {
                result = "True";
            }
            else
            {
                result = "False";
            }              
            }            
    });
    return result;
}



    // VAL: Function Name Allowed
    public JsonResult FunAllowed(string FunctionName)
    {            
        var records = db.Functions.Where(x => x.FunctionName == FunctionName).ToList();
        string result = "False";

        if (records.Count > 0)
            result = "True";

        return Json(records, JsonRequestBehavior.AllowGet);
    }

ReferenceError: response is not defined at eval (eval at AllowedFunction ( http://localhost:52613/Functions/Create:50:9 ), :1:1) 1. message: "response is not defined" 2. stack: "ReferenceError: response is not defined

I think it's probably because your FunAllowed function is expecting a string , but you're passing an object with a property named FunctionName which is a string .

I think if you did this it might work without changing your JS code:

class FunAllowedinput
{
    public string FunctionName{get;set;}
}
public JsonResult FunAllowed(FunAllowedInput input)
{            
    var records = db.Functions.Where(x => x.FunctionName == input.FunctionName).ToList();
    string result = "False";

    if (records.Count > 0)
        result = "True";

    return Json(records, JsonRequestBehavior.AllowGet);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM