Ajax在AspNetMvc错误请求中

本文关键字:请求 错误 AspNetMvc Ajax | 更新日期: 2023-09-27 18:22:30

我有一个简单的页面:

<div style="width:600px; margin-left:auto; margin-right:auto">
    <div style="background-color: lightgray">
        <h2>My Products</h2>
    </div>
    <p>Click the button to Get Products with an Ajax call</p>
    <input id="btnAjax" name="btnAjax" type="button" value="Get Products" />
    <div id="products" style="background-color:lightskyblue">
        <div id='loadingmessage' style='display:none'>
            loading...
        </div>
    </div>
</div>

和章节脚本:

@section Scripts {
        @*@Scripts.Render("~/bundles/jqueryval")*@
    <script>
        $('#btnAjax').click(function () {
            $.ajax({
                url: '/Test/GetProducts',
                contentType: 'application/html; charset=utf-8',
                data: { id: 1 },
                type: 'GET',
                dataType: 'html'
            })     
            .success(function (result) {
                $('#products').html(result);
                $('#loadingmessage').hide();
            })
            .error(function (xhr, status, throwError) {
                alert(status);
            })           
        });
        </script>
    }

TestController中的方法名称GetProducts(int id):

    public PartialViewResult GetProducts(int id)
    {
        var listOfCourses = db.Courses.ToList();
        Task.Delay(9000000);
        if(id == 1)  
            throw new Exception("something bad");
        return PartialView("_GetProducts", listOfCourses);
    }

有没有办法在按钮(#btnAjax)中设置"id"并将其抛出到ajax脚本?例如:

<input id="btnAjax" name="btnAjax" type="button" value="Get Products" data:id="1" />

然后在ajax脚本中读取

data: { id: $(this).id

第二个问题是如何从错误事件中的异常("something bad")

Ajax在AspNetMvc错误请求中

中获取消息错误

将其设置为数据属性,例如data-id:

<input id="btnAjax" name="btnAjax" type="button" value="Get Products" data-id="1" />

要阅读它,你可以使用以下任意一种:

$("input#btnAjax").attr("data-id")

$("input#btnAjax").data("id")

第二种选择是最新的方法。

编辑:

对于第二个问题,您需要返回JSON,例如

public ActionResult GetProducts(int id)
{
    var listOfCourses = db.Courses.ToList();
    Task.Delay(9000000);
    if (id == 1)
    {
        Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return Json(new { ErrorMessage = "Test" }, JsonRequestBehavior.AllowGet);
    }
    return PartialView("_GetProducts", listOfCourses);
}

我认为以上应该有效(我自己还没有机会尝试)。通过将状态代码设置为错误代码(而不是200 status OK),您应该在JavaScript的AJAX代码中点击error函数。

我不能百分之百肯定这一点,但我回答的第一部分肯定对你有用。