Ajax总是继续发生错误' (C#MVC 5)关于跨域请求

时间:2016-10-13 17:57:00

标签: c# jquery ajax asp.net-mvc cross-domain

我有这个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调用

的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值的东西)并且不使用Bind或任何东西,但这与问题无关

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

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

2 个答案:

答案 0 :(得分:0)

首先, 您绝不应该使用正则表达式来验证电子邮件地址。查看this

其次,您希望在ASP.Net MVC中使用 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>

视图

public class UserModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Country { get; set; }
    public string Email { get; set; }
}

控制器

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

答案 1 :(得分:0)

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

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

在web.config上:|

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

我忘了说,但这是一个交叉来源请求:|