本文介绍了为什么我的AJAXoned行动的回报不被看作是呼​​叫者成功?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ASP.NET MVC应用程序,我有这个AJAX调用在我看来的剧本部分:

In my ASP.NET MVC app, I've got this AJAX call in my View's script section:

$(".ckbx").change(function () {
. . .
    $.ajax({
        type: 'GET',
        url: '@Url.Action("GetUnitReportPairVals", "Home")',
        data: { unit: unitval, report: rptval },
        cache: false,
        success: function (result) {
            alert(result);
        }
    });
});

步进通过控制器的动作被称为:

Stepping through the Controller action being called:

public ActionResult GetUnitReportPairVals(string unit, string report)
{
    HomeModel model = new HomeModel();

    int rptId = GetReportIDForName(report);

    DataTable UnitReportPairEmailValsDT = new DataTable();
    UnitReportPairEmailValsDT = SQL.ExecuteSQLReturnDataTable(
        SQL.UnitReportPairEmailQuery,
        CommandType.Text,
        new SqlParameter()
                {
                    ParameterName = "@Unit",
                    SqlDbType = SqlDbType.VarChar,
                    Value = unit
                },
                new SqlParameter()
                {
                    ParameterName = "@RptID",
                    SqlDbType = SqlDbType.Int,
                    Value = rptId
                }
                );

    model.UnitReportPairEmailVals = UnitReportPairEmailValsDT;
    return View(model);
}

......这一切似乎做工精细; 模式包含UnitReportPairEmailVals的预期值。

...it all seems to be working fine; "model" contains the expected value in UnitReportPairEmailVals.

但我从来没有看到警告信息从这里Ajax调用:

But I never see the alert message from here in the Ajax call:

success: function (result) {
    alert(result);
}

那么,为什么没有达到jQuery的AJAX调用的成功的功能?

So why is the "success" function of the jQuery AJAX call not being reached?

顺便说一句,这可能是一个线索:我的控制器方法的最后一行:

BTW, this may be a clue: the final line of my Controller method:

return View(model);

...油漆字查看红色作为罗德岛公鸡的梳子。但是,如果它不应该是,它是什么应该是?这就是我在我的公众的ActionResult指数()控制器动作,这正常工作的结束同样的事情。

...paints the word "View" red as a Rhode Island rooster's comb. But if it's not supposed to be that, what is it supposed to be? That's the exact same thing I have at the end of my "public ActionResult Index()" controller Action, which works fine.

我改变了我到底Ajax调用为:

I changed the end of my Ajax call to:

success: function (result) {
    alert(result);
},
failure: function (error) {
    alert(error);
}

......我的控制器方法的末尾:

...and the end of my Controller method to:

return Json(new { Result = model }, JsonRequestBehavior.AllowGet);

...但我没有得到任何警告,无论是从成功中也没有从失败的。

...but I get no alert, neither from success nor from failure.

请注意:当我试图这样的:

Note: When I tried this:

var model = JSON.stringify({ unit: unitval, report: rptval });
    $.ajax({
        type: 'GET',
        url: '@Url.Action("GetUnitReportPairVals", "Home")',
        data: model,
        contentType: 'application/json',
        cache: false,
        success: function (result) {
            alert(result);
        },
        error: function (result) {
            debugger;
        }
    });

...单位为空,所以它不会飞的。

..."unit" was null, and so it wouldn't fly at all.

当我改成了这个(除去1号线,改变了数据ARG回到我一直在使用pviously $ P $过):

When I changed it to this (removed line 1 and changed the "data" arg back to what I had been using previously):

$.ajax({
    type: 'GET',
    url: '@Url.Action("GetUnitReportPairVals", "Home")',
    data: { unit: unitval, report: rptval },
    contentType: 'application/json',
    cache: false,
    success: function (result) {
        alert(result);
    },
    error: function (result) {
        alert('failed');
    }
});

...单位是什么,我希望它是(和报告也是如此),但我最终看到'失败'。

..."unit" is what I expect it to be (and "report", too), but I ultimately see 'failed'.

在我拼凑出几个不同的答案,这与相关的问题,我写了关于如何做到这一点的。

Once I pieced together several different answers to this and related questions, I wrote up a tip on how to do this here.

我有了这个[工作] Ajax调用[工作]:

I've got this [working] ajax call [working]:

var model = JSON.stringify({ unit: unitval, report: 1 });
$.ajax({
    type: 'GET',
    url: '@Url.Action("GetUnitDataRangeParamsVals", "UnitReportDataRangeParams")',
    data: { unit: unitval, report: 1 },
    contentType: 'application/json',
    cache: false,
    success: function (returneddata) {
        populatedatarangeprams(1, returneddata);
    },
    error: function () {
        alert('error - returneddata.error.stringify');
    }
});

...但我没有使用的声明的样板,而据我的理解,它是搭配的contentType:应用/ JSON的,

...but I'm not using the "model" that's declared and, according to my understanding, it is paired with "contentType: 'application/json',"

所以我想我应该做的就是这样的事情,而不是:

So I thought what I should do is something like this instead:

var model = JSON.stringify({ unit: unitval, report: 1 });
$.ajax({
    type: 'GET',
    url: '@Url.Action("GetUnitDataRangeParamsVals", "UnitReportDataRangeParams")',
    data: model,
    contentType: 'application/json',
    cache: false,
    success: function (returneddata) {
        populatedatarangeprams(1, returneddata);
    },
    error: function () {
        alert('error - returneddata.error.stringify');
    }
});

现在传递给控制器​​的方法将数据以JSON字符串化格式(封装在模式)。

Now the data passed to the controller's method is in json stringified format (encapsulated in "model").

但是,它甚至不工作

它与第一个块,但不是第二

It works with the first block, but not the second.

所以我移除了模式和的contentType线路,并改变了数据行回到它一直是,而且它工作正常。那么,他们没用,还是我使用他们的错?

So I removed both the "model" and the "contentType" lines, and changed the "data" line back to what it had been, and it works fine. So are they useless, or am I employing them wrongly?

推荐答案

下面是ASP.NET MVC做阿贾克斯时,我用几个片段。

Here are a few snippets I use when doing ajax in ASP.NET MVC.

$(".ckbx").change(function () {
    .....
    var model = JSON.stringify({ unit: unitval, report: rptval });
    $.ajax({
        type: 'GET',
        url: '@Url.Action("GetUnitReportPairVals", "Home")',
        data: model,
        contentType: 'application/json',
        cache: false,
        success: function (result) {
            alert(result);
        },
        error: function(result) {
            debugger;
        }
    });
});

有时,这些两个变化(相对于原来的)不是必要的,但ASP.NET可以稍微挑剔,如果JSON是不是恰到好处,这有助于这一点。既然你能步入控制器的方法,这是不是你的问题,但它可以派上用场了。

Sometimes those two changes (as compared to your original) are not necessary but ASP.NET can be slightly picky if the json isn't just right and this helps with that. Since you are able to step into the controller method, this wasn't your problem, but it can be handy.

您真正的问题是在控制方法的返回类型。的ActionResult意味着它要寻找一个相应的视图,并建立了基于该视图的HTML。但是,如果你从事的是Ajax,那么你可能不希望这样。

Your real problem was the return type on the controller method. ActionResult means it is going to look for a corresponding view and build out the html based on that view. But if you are doing ajax then you probably don't want that.

public JsonResult GetUnitReportPairVals(string unit, string report)
{
    // do some stuff
    // then create response model
    var model = ...//whatever data you are returning here
    return Json(model);
}

这是在ASP.NET MVC Ajax调用标准的做法。

This is the "standard" approach for ajax calls in ASP.NET MVC.

当您在您的评论指出,在的ActionResult指数方法的伟大工程。是的,因为该索引方法的目的是要加载的页面。一般来说,如果是用来加载页面的方法,那么您将使用的ActionResult,因为它会使用一个视图来创建该页面的HTML。但是,如果你是刚刚提交的信息,然后再返回,如成功的响应,那么你不想整个HTML响应,你要JSON。这就是为什么JsonResult在这里工作。

As you noted in your comment, ActionResult works great in the Index method. Yes, because the purpose of the index method is to load a page. Generally, if the method is used to load a page then you'll use ActionResult because it will use a view to create the html for that page. But if you are just submitting info and then returning a response like "success" then you don't want a whole html response, you want json. That's why JsonResult works here.

这篇关于为什么我的AJAXoned行动的回报不被看作是呼​​叫者成功?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 20:33
查看更多