1

我的页面中有一些 ajax 表单,当调用 OnSuccess 函数时,我需要获取表单 ID 或表单内的某些元素,例如:

<li>
    @using (Ajax.BeginForm(new AjaxOptions
    {
        OnSuccess = "form.onSuccess"
    }))
    {

        @Html.TextBoxFor(m => m.TaskId)

        <button type="submit">Save</button>
    }
</li>

我怎样才能得到?

4

1 回答 1

2

选项1:

@using (Ajax.BeginForm(new AjaxOptions{OnComplete = "DefaultEditOnComplete(xhr, status, 'Person')"}))
{
    //Person data and submit button
}

function DefaultEditOnComplete(xhr, status, entityName) {

    //xhr - the ajax response
    //status - the response text, ex. "success"
    //entityName - your custom argument, in this example 'Person'

    alert('DefaultEditOnComplete fired for ' + entityName);
}

选项 2:

 $('form').submit(function () {
   $(this).addClass('activeForm');
 });

 @using (Ajax.BeginForm(new AjaxOptions{OnSuccess= "JaxSuccess(xhr, status)"}))
{
    ....
}

function JaxSuccess(xhr, status) {
 var active = $(".activeForm");

 //Do some stuff here
 .....

 //When Done, remove the activeForm class, making everything clean
 $(".activeForm").removeClass('activeForm');
}

选项 3:放弃 Ajax.BeginForm,并替换常规表单和 jquery 配对:

@using (Html.BeginForm("SomethingNice", "Home", FormMethod.Post, new { @id = "CoolForm", @class = "ajaxForm" }))
{
     @Html.LabelFor(m => m.Rating)
    @Html.TextBoxFor(m => m.Rating)
    @Html.LabelFor(m => m.Comment)
    @Html.TextBoxFor(m => m.Comment)
    <input type="submit" value="Submit"/>
}
   <script type="text/javascript">
    $(function() {
        $(".ajaxForm").submit(function(e) {
            e.preventDefault();
            var form = $(this);
            var jaxUrl = form.attr('action');
            var dat = form.serialize();
            alert(form.attr('id'));
            $.ajax({
                url: jaxUrl,
                data: dat,
                success: function(data) {
                    form.parent().append(data);
                },
                error: function(xhr, status) {

                }
            });

        });
    });
</script>
于 2012-11-30T19:48:45.950 回答