MVC:使用Jquery.ajax()将参数传递给action

时间:2012-10-27 12:31:42

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

我对MVC很新。我需要ajax使用Action使用参数调用html.Action()。我无法通过这个......

希望它对其他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中的操作。它被用在页面上的某个地方。但是我不能以某种方式使用它......

请说明我做错了...

3 个答案:

答案 0 :(得分:4)

看起来您在单击链接时尝试使用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调用。

答案 1 :(得分:1)

改变你的行动:

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

            }
        });           
    }

答案 2 :(得分:1)

答案中的问题是行动的网址不完整..我是用这种方式做的

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

            }
        });
    }
相关问题