简体   繁体   English

MVC Ajax呼叫问题

[英]MVC Ajax Call issue

In an MVC view I have, 在MVC视图中,

a submit button where, I check for all the validation. 一个提交按钮,我检查所有验证。 If the validation is wrong I returns false. 如果验证错误,则返回false。 So that the form will not post. 这样表单就不会发布。

However I was checking for a duplicate check using Ajax get method. 但是我正在使用Ajax get方法检查重复检查。 It will return true if the value exists. 如果该值存在,它将返回true。 Then I will return false for the button submit. 然后,对于按钮提交,我将返回false。

However in my case the ajax call is not returning anything. 但是在我的情况下,ajax调用未返回任何内容。 Or rather the process doesn't wait for the ajax to come back. 或者更确切地说,该过程不等待ajax回来。 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: CheckAjax代码:

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请求是异步的,因此您必须使用回调执行此操作,或者(不建议)添加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. 再详细一点,在CheckAjax方法中声明结果变量,并在请求完成时为其分配值,然后返回此变量。

尝试这个

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

on alerting only the 'returndata' you able to see "true" or "false"? 在仅警告“ returndata”时,您能够看到“ true”或“ false”? ,try quoting them in your condition and give e.preventDefault a shot instead of return false ,请尝试根据您的情况报价,并给e.preventDefault射击,而不是返回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 问候

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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