【问题标题】:MVC: pass parameter to action using Jquery.ajax()MVC:使用 Jquery.ajax() 将参数传递给操作
【发布时间】:2012-10-17 12:03:38
【问题描述】:

我对@9​​87654321@ 还很陌生。我需要使用html.Action() 使用参数对Action 进行ajax 调用。我无法通过这个..

希望它对其他 MVC 初学者也有帮助..

HTML:

<%: Html.ActionLink("Add Race", "AddRace", 
        new {eventId = Model.EventId, fleetId=Model.SelectedFleet.ID}, 
        new{@onclick=string.Format("return checkFleetAddedandScroing()")}) %>

Jquery:

 function checkFleetAddedandScroing() {
        debugger;
        $.ajax({
            type: "GET",
            url: '<%=Url.Action("CheckFleetExists")%>',
            dataType: "json",
            cache: false,
            success: function (data, textStatus) {
                data = eval("(" + data + ")");
                if (data == true) {
                    return true;
                }
                else {
                    alert("Cannot Add race becasue you have not yet added any fleets and fleet scoring is checked.");
                    return false;
                }
            }, //success
            error: function (req) {

            }
        });           
    }

行动:

  public JsonResult CheckFleetExists(Guid fleetId )
    {
        bool exists = false;
        try
        {
            exists = !db.Races.Any(r => r.FleetID == fleetId);
        }
        catch
        {
        }
        return Json(exists, JsonRequestBehavior.AllowGet);
    }

我需要将fleetid 传递给Model.SelectedFleet.ID 中的操作。它在页面上的某个地方使用。但我无法以某种方式使用它..

请提出我做错的地方...

【问题讨论】:

  • 你检查过你的动作是否击中了吗?
  • no..它没有被击中...而是显示警告消息,该消息写在成功的其他部分..
  • 它没有被击中,因为动作CheckFleetExists总是返回false,你的JavaScript函数也总是返回false。您在哪里或如何将 GUID 传递给 CheckFleetExists?
  • 我认为你有两个错误,一个是 agarhy 建议的。第二个是 onclick 之前的@符号。
  • 而且,顺便说一下,Json 方法默认情况下不允许 GET 请求是有原因的。是为了防止劫持。考虑改为对 JSON 数据发出 POST 请求。

标签: asp.net-mvc jquery parameter-passing


【解决方案1】:

看起来您正在尝试在单击链接时使用 AJAX 调用控制器操作,并且根据此调用的结果,允许用户重定向到实际的 AddRace 操作或提示错误消息.

您的代码的问题是您试图从成功的 AJAX 回调中返回 true/false,这没有任何意义。您需要始终从点击回调和成功回调中返回 false,根据服务器返回的值,使用 window.location.href 函数手动重定向。

HTML:

<%: Html.ActionLink(
    "Add Race", 
    "AddRace", 
    new {
        eventId = Model.EventId, 
        fleetId = Model.SelectedFleet.ID
    }, 
    new {
        data_fleetid = Model.SelectedFleet.ID,
        @class = "addRace"
    }
) %>

Jquery:

<script type="text/javascript">
    $(function () {
        $('.addRace').click(function (evt) {
            $.ajax({
                type: 'GET',
                url: '<%= Url.Action("CheckFleetExists") %>',
                cache: false,
                data: { fleetId: $(this).data('fleetid') },
                success: function (data) {
                    if (data.exists) {
                        // the controller action returned true => we can redirect
                        // to the original url:
                        window.location.href = url;
                    }
                    else {
                        alert("Cannot Add race becasue you have not yet added any fleets and fleet scoring is checked.");
                    }
                },
                error: function (req) {

                }
            });

            // we make sure to cancel the default action of the link
            // because we will be sending an AJAX call
            return false;
        });
    });
</script>

行动:

public ActionResult CheckFleetExists(Guid fleetId)
{
    bool exists = false;
    try
    {
        exists = !db.Races.Any(r => r.FleetID == fleetId);
    }
    catch
    {
    }
    return Json(new { exists = exists }, JsonRequestBehavior.AllowGet);
}

备注:在您的AddRace 控制器操作中不要忘记执行与您在CheckFleetExists 中执行相同的验证。用户可以简单地禁用 javascript,AJAX 调用将永远不会完成。

【讨论】:

  • 这个也不能打断点放在action..感谢你的支持Darin..+1为你..我自己的努力解决了..
  • 我已经相应地更新了我的答案。在您的示例中,您仍然从错误的成功回调中返回真/假。您不会从 checkFleetAddedandScroing 函数本身返回 false,因此您不会取消默认操作。
  • 哦,这就是为什么它总是返回 false.. 并且每次都显示消息框.. 并且无论return false 声明如何都重定向.. 是这样,达林..?
  • 它总是重定向,因为你永远不会从不正确的点击处理程序返回 false。
  • 抱歉,Darin,之前没有接受您的回答。 :D 非常感谢你让我更清楚地了解$.ajax()..我对此有点困惑..但是你的工作对我来说很棒的stackoverflow.com/questions/9422215/…..你是真正的MVC SO..thanks很多.. :)
【解决方案2】:

问题在于操作的 url 不完整的答案..我用这种方式做到了

function checkFleetAddedandScroing() {
       // debugger;
        $.ajax({
            type: "POST",
            url: '<%=Url.Action("CheckFleetExists", new {eventId=Model.EventId})%>',
            dataType: "json",                
            cache: false,
            success: function (data, textStatus) {
                data = eval("(" + data + ")");
                if (data == true) {
                    return true;
                }
                else {
                    alert("Cannot Add race becasue you have not yet added any fleets and fleet scoring is checked.");
                    return false;
                }
            }, //success
            error: function (req) {

            }
        });
    }

【讨论】:

    【解决方案3】:

    像这样改变你的行为:

     public JsonResult CheckFleetExists(string fleetId)
        {
            var fleetGuid = Guid.Parse(fleetId);
            bool exists = false;
            try
            {
                exists = !db.Races.Any(r => r.FleetID == fleetGuid );
            }
            catch
            {
            }
            return new JsonResult{ Data = exists};
        }
    

    然后改变你的 ActionLink :

    <%: Html.ActionLink("Add Race", "AddRace", 
        new {eventId = Model.EventId, fleetId=Model.SelectedFleet.ID}, 
        new{onclick=string.Format("return checkFleetAddedandScroing({0})",Model.SelectedFleet.ID)}) %>
    

    你的脚本块可能看起来像这样:

    function checkFleetAddedandScroing($fleetId) {
            $.ajax({
                type: "POST",
                url: '<%=Url.Action("CheckFleetExists")%>',
                dataType: "json",
                data : { "fleetId" : $fleetId },
                cache: false,
                success: function (data, textStatus) {
                    data = eval("(" + data + ")");
                    if (data == true) {
                        return true;
                    }
                    else {
                        alert("Cannot Add race becasue you have not yet added any fleets and fleet scoring is checked.");
                        return false;
                    }
                }, //success
                error: function (req) {
    
                }
            });           
        }
    

    【讨论】:

    • 我认为他可能对checkFleetAddedandScroing JavaScript 函数也有问题。我认为他没有将任何数据传递给 AJAX 请求中的操作。不过我现在懒得纠正了。你介意做荣誉吗? :)
    • 它没有工作,即使它无法命中设置在动作上的断点..但我以某种方式解决了它..但是它让我进步了很多..+1 为你..
    猜你喜欢
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 2011-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多