方法不能只从AJAX调用

时间:2016-05-12 09:11:19

标签: jquery ajax asp.net-mvc database

我已经在互联网上搜索了几个小时,但我还没弄清楚为什么这不起作用。

我希望用户填写并形成并将该表单保存在数据库中,这很简单。在我把我的ajax之前的东西放进去之前,它完美无缺。但现在它不断提出错误:Sorry, this method can't be called only from AJAX.

这是我的代码 -

控制器:

// GET: /AjaxStuff/Create
        public ActionResult Contact()
        {
            return View();
        }

        // POST: /AjaxStuff/Create
        [HttpPost]
        public ActionResult Contact(Users usertocreate)
        {
            if (!Request.IsAjaxRequest())
            {
                Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
                return Content("Sorry, this method can't be called only from AJAX.");
            }
            try
            {
                if (ModelState.IsValid)
                {
                    _db.Table.Add(usertocreate);
                    _db.SaveChanges();
                    return Content("Record added successfully !");
                }
                else
                {
                    StringBuilder strB = new StringBuilder(500);
                    foreach (ModelState modelState in ModelState.Values)
                    {
                        foreach (ModelError error in modelState.Errors)
                        {
                            strB.Append(error.ErrorMessage + ".");
                        }
                    }
                    Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
                    return Content(strB.ToString());
                }
            }
            catch (Exception ee)
            {
                Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
                return Content("Sorry, an error occured." + ee.Message);
            }
        }

查看:

@model Site01.Models.Users

@{
    ViewBag.Title = "Contact";

    AjaxOptions options = new AjaxOptions
    {
        Confirm = "Are you sure to save record?",
        OnBegin = "OnBeginMethod",
        OnFailure = "OnFailtureMethod",
        OnSuccess = "OnSuccessMethod",
        OnComplete = "OnCompleteMethod"
    };
}

<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

<h3>Deixe-nos uma mensagem!</h3>
<p>Duvidas ou apenas a deixar um comentário? Preencha o formulário!</p>
@using (Ajax.BeginForm(options))
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Nome, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Nome, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Nome, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Idade, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Idade, new
                   {
                       htmlAttributes = new { @class = "form-control" }
                   })
                @Html.ValidationMessageFor(model => model.Idade, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Tel, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="checkbox">
                    @Html.EditorFor(model => model.Tel)
                    @Html.ValidationMessageFor(model => model.Tel, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.DataNas, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="checkbox">
                    @Html.EditorFor(model => model.DataNas)
                    @Html.ValidationMessageFor(model => model.DataNas, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.CP, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="checkbox">
                    @Html.EditorFor(model => model.CP)
                    @Html.ValidationMessageFor(model => model.CP, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Localidade, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="checkbox">
                    @Html.EditorFor(model => model.Localidade)
                    @Html.ValidationMessageFor(model => model.Localidade, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Mensagem, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="checkbox">
                    @Html.EditorFor(model => model.Mensagem)
                    @Html.ValidationMessageFor(model => model.Mensagem, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
                <label id="labelAjaxStatus" class="alert-warning"></label>
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Ver Lista", "User")
</div>

<script type="text/javascript">
    var isError = false;
    function OnBeginMethod() {
        $("#labelAjaxStatus").text("Carregar ....");
    }

    function OnFailtureMethod(error) {
        $("#labelAjaxStatus").text("Ocorreu um erro." + error.responseText);
        isError = true;
    }

    function OnSuccessMethod(data) {
        $("#labelAjaxStatus").text("Dados foram guardados com sucesso!");
        $("#Nome").val('');
        $("#Idade").val('');
        $("#Email").val('');
        $("#Tel").val('');
        $("#DataNas").val('');
        $("#CP").val('');
        $("#Localidade").val('');
        $("#Mensagem").val('');
    }

    function OnCompleteMethod(data, status) {
        if (!isError) {
            $("#labelAjaxStatus").text("Status do processo: " +
            status);
        }
    }
</script>

@Scripts.Render("~/bundles/jqueryval")

不要介意葡萄牙语。 谁知道我做错了什么?

2 个答案:

答案 0 :(得分:0)

如果您要使用Contact

,则需要从控制器操作ajax中删除以下代码段
if (!Request.IsAjaxRequest())
{
    Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
    return Content("Sorry, this method can't be called only from AJAX.");
}

答案 1 :(得分:0)

你可以添加一个将插入你的数据库(php,perl)的脚本。所以ajax只会将数据发送到脚本,一个完成就会显示状态。