Ajax.BeginForm - 获取发出请求的元素

时间:2012-11-30 18:34:18

标签: asp.net-mvc

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

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

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

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

我怎么能得到?

1 个答案:

答案 0 :(得分: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>