Marek Woźniak
Marek Woźniak

Reputation: 1786

Ajax in AspNetMvc error request

i have simple page:

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

and section Script:

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

method in TestController names 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);
    }

Is any way to set 'id' in button (#btnAjax) and throw it to ajax script? for example:

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

and then read it in ajax script

data: { id: $(this).id

??

The second question is how I can get message error from exception in error event ("something bad")

Upvotes: 0

Views: 56

Answers (1)

Jason Evans
Jason Evans

Reputation: 29186

Set it as a data attribute e.g. data-id:

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

and to read it you can use either of these:

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

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

The second option is the most up to date way of doing this.

EDIT:

For your second question, you need to return JSON e.g.

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

I think the above should work (I haven't had a chance to try this myself). By setting the status code to an error code (and not 200 STATUS OK), you should hit the error function in the AJAX code in your JavaScript.

I'm not 100% sure about this bit, but certainly my first part of my answer should work for you.

Upvotes: 1

Related Questions