Ajax总是继续'Error'(c# MVC 5)跨域请求

本文关键字:请求 MVC Error 继续 Ajax | 更新日期: 2023-09-27 18:12:53

我有这个c#方法:

c#

[HttpPost]
[AllowAnonymous]
public JsonResult PostOnCRM(string textBoxFirstName, string textBoxCountry, string textBoxLastName, string textBoxEmail, string textBoxTitle, string textBoxTelephone, string textBoxCompany, string textBoxWebsite, string textAreaNote, string checkBoxUpdates)
{
        bool isValidEmail = Regex.IsMatch(textBoxEmail,
        @"^(?("")("".+?(?<!'')""@)|(([0-9a-z](('.(?!'.))|[-!#'$%&''*'+/='?'^`'{'}'|~'w])*)(?<=[0-9a-z])@))" +
        @"(?('[)('[('d{1,3}'.){3}'d{1,3}'])|(([0-9a-z][-'w]*[0-9a-z]*'.)+[a-z0-9]['-a-z0-9]{0,22}[a-z0-9]))$",
        RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
        if (!isValidEmail)
            throw new Exception("E-mail is not a valid one");
        LeadInformation lead = new LeadInformation()
        {
            Subject = "Web site",
            FirstName = textBoxFirstName,
            LastName = textBoxLastName,
            JobTitle = textBoxTitle,
            Address1_Country = textBoxCountry,
            EmailAddress1 = textBoxEmail,
            MobilePhone = textBoxTelephone,
            WebsiteUrl = textBoxWebsite,
            Description = textAreaNote,
            DoNotEmail = checkBoxUpdates.Contains("Yes") ? true : false
        };

        //Some method that works well go here
        return Json(new { success = true, responseText = "Your message successfuly sent!" }, JsonRequestBehavior.AllowGet);
}
在我看来,这个Ajax调用

$("#formContact").submit(function (evt) {
evt.preventDefault();
var formdata = $('form').serialize();
$.ajax({
    type: 'POST',
    dataType: "json",
    cache: false,
    url: 'http://localhost:59289/Lead/PostOnCRM',
    data: formdata,
    success: function (response) {
        alert('success!');
    },
    error: function (response) {
        alert('Error! try again later');
    }
});
});

该方法执行完美。在数据库中插入,但当它返回到ajax方法时,它总是落在"错误"上,不返回我发送的响应。会是什么呢?

很抱歉以这种方式接受参数(特别是bool值的东西)并且不使用绑定或其他东西,但这与问题无关

我在葡萄牙的StackOverflow上问过这个问题,但是没有一个好的答案。

这是我的浏览器的打印https://postimg.cc/image/e86q3hcol/

Ajax总是继续'Error'(c# MVC 5)跨域请求

首先,你不应该使用正则表达式来验证电子邮件地址。看看这个。

第二,你想在ASP中使用Model。而不是在action方法中声明多个参数。

请做它属性。如果你还有问题,请回来再问。下面是一个工作示例-

视图

@model UserModel
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm())
    {
        @Html.TextBoxFor(model => model.Email)
        <button id="btnSubmit" type="button">Submit</button>
    }
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>
        $(function () {
            $("#btnSubmit").click(function () {
                var data = {
                    Email: $("#Email").val()
                };
                $.ajax({
                    type: 'POST',
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    url: "@Url.Action("PostOnCRM", "Lead")",
                    data: JSON.stringify(data),
                    success: function (response) {
                        alert('success!');
                    },
                    error: function (response) {
                        alert('Error! try again later');
                    }
                });
            });
        });
    </script>
</body>
</html>
<<h2>视图/h2>
public class UserModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Country { get; set; }
    public string Email { get; set; }
}
h2控制器

public class LeadController : Controller
{
    public ActionResult Index()
    {    
        return View();
    }
    [HttpPost]
    [AllowAnonymous]
    public JsonResult PostOnCRM(UserModel model)
    {
        bool isValidEmail = IsValidEmail(model.Email);
        if (!isValidEmail)
            throw new Exception("E-mail is not a valid one");
        // ...
        return Json(new { success = true, responseText = "Your message successfuly sent!" });
    }
    public static bool IsValidEmail(string email)
    {
        if (String.IsNullOrWhiteSpace(email))
            return false;
        try
        {
            email = new MailAddress(email).Address;
            return true;
        }
        catch (FormatException)
        {
            return false;
        }
    }
}

我的老板在5分钟内解决了我的问题(我尝试了2天)

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
  </customHeaders>
</httpProtocol>

web。配置:|

我不知道为什么。有人能解释一下吗?

我忘记说了,这是一个跨域请求:|