0

我正在尝试从我的剃刀视图提交一个 ajax 表单,并且我希望控制器返回一个 JSON 对象。当我使用 ("#form0").submit(alert("hi");); 数据进入控制器,我收到警报。但是,当我使用 ("#form0").submit(function(){alert("hi");}); 数据没有通过,我也没有收到警报。我觉得这对我缺少的语法来说是次要的。以下是相关代码:

jQuery:

$(function () {
//setting up the schedule modal dialoag.
$("#schedModal").dialog({
    buttons: {
        Submit:
                function () {
                    $("#form0").ajaxSubmit(function () {
                        //this is where I want to put the magic, but I need the alert to fire first.
                        alert("hi");
                        return false;
                    });
                },
        Cancel:
                function () {
                    $(this).dialog("close");
                }
    },
    autoOpen: false,
    minHeight: 350,
    modal: true,
    resizable: false
});

目标视图:

@model FSDS.DataModels.Schedule

@using (Ajax.BeginForm("scheduleNew", null, new AjaxOptions { UpdateTargetId = "partial" }, new {}))
{
@Html.ValidationSummary(true)

    <div class="editor-label">
        @Html.LabelFor(model => model.ScheduleName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.ScheduleName)
        @Html.ValidationMessageFor(model => model.ScheduleName)
    </div>

    @* tons of other labels and editor fields go in here, omitted for brevity. *@
}

控制器,如果这很重要:

    [HttpPost]
    public ActionResult scheduleNew(Schedule schedule)
    {
        if (Request.HttpMethod == "POST")
        {
            FSDSDBEntities context = new FSDSDBEntities();

            if (ModelState.IsValid)
            {
                context.Schedules.AddObject(schedule);
                context.SaveChanges();
            }

            return Json(schedule);
        }
        else
        {
            return PartialView();
        }
    }
4

1 回答 1

2

只需使用$('#form0').submit();

Submit: function () {
    $('#form0').submit();
}

然后在 AjaxForm 中定义一个OnSuccess处理程序,当 AJAX 请求成功时将调用该处理程序:

@using (Ajax.BeginForm("scheduleNew", null, new AjaxOptions { OnSuccess = "success", UpdateTargetId = "partial" }, new {}))

最后success是javascript处理程序:

function success(data) {
    // the form was successfully submitted using an AJAX call.
    // here you could test whether the data parameter
    // represents a JSON object or a partial view
    if (data.ScheduleName) {
        // the controller action returned the schedule JSON object
        // => act accordingly
    } else {
        // the controller action returned a partial view
        // => act accordingly
    }
}
于 2012-08-06T16:54:39.130 回答