简体   繁体   中英

MVC Ajax Call issue

In an MVC view I have,

a submit button where, I check for all the validation. If the validation is wrong I returns false. So that the form will not post.

However I was checking for a duplicate check using Ajax get method. It will return true if the value exists. Then I will return false for the button submit.

However in my case the ajax call is not returning anything. Or rather the process doesn't wait for the ajax to come back. Is there anyway can I achieve it.

My Code on button click

var isDraftValid = 0;
        if(checkAjax()==false)
        {
            isDraftValid++;
        }
        if(check2()==false)
        {
            isDraftValid++;
        }
        if(isDraftValid>0)
        {
          return false;
        }

CheckAjax Code:

var href = '@Url.Action("IsDuplicate", "Book")' + '/' + bTitleVal;
$.ajax({
    type: "get",
    url: href,
    dataType: "json",
    traditional: true,
    cache: false,
    contentType: 'application/json',
    //data: JSON.stringify({ bookTitle: bTitleVal }),
    data: {},
    success: function (returndata) {
        debugger;
        if (returndata == true) {
            return true;
        }
        else {
            return false;
        }
    },
    error: function (arg, data, value) {
    }
});

You ajax request is asynchronous, so you must do it with callbacks, or (not recommended) add async: false:

$.ajax({
    type: "get",
    url: href,
    async: false

One more detail, declare result variable in CheckAjax method and assign value to it when request completes and then return this variable.

尝试这个

var href = '@Url.Action("IsDuplicate", "Book",new{bTitleVal=bTitleVal})' 

on alerting only the 'returndata' you able to see "true" or "false"? ,try quoting them in your condition and give e.preventDefault a shot instead of return false

Maybe you could use a different call sequence like this :

dataOk = true;
if(!check2())
{
    dataOk = false;
}
if(dataOk))
{
    dataOk = checkAjax();
}
return dataOk;

Or maybe I did not understand your request ?

Regards

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