如何使用单选按钮更改事件提交AJAX表单?

时间:2013-07-15 10:40:48

标签: c# asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我有一个AJAX表格&我想在单选按钮更改事件中提交它。

AJAX表格:

     @using (Ajax.BeginForm("Vote", "Rate", null ,
                       new AjaxOptions
                           {
                               InsertionMode = InsertionMode.Replace,
                               HttpMethod = "GET",
                               OnFailure = "searchFailed",
                               LoadingElementId = "ajax-loader",
                               UpdateTargetId = "searchresults",
                           },new { id = "voteForm" }))
                {
                <input type="radio" name="Stars" value="1">
                <input type="radio" name="Stars" value="2">
                <input type="radio" name="Stars" value="3">

                }

我使用以下代码但不起作用。

       $("#voteForm").ajaxSubmit({ url: '/Vote/Vote', type: 'get' });

2 个答案:

答案 0 :(得分:0)

试试这个:

<script type="text/javascript">
    $(function () {
        $("input[name='Stars']").change(function() {
            $("#voteForm").ajaxSubmit({ url: '/Vote/Vote', type: 'get' });
        });
    });
</script>

答案 1 :(得分:0)

@Babul Mirdha Ajax.BeginForm是一种工作正常的机制,但是定制与标准截然不同的特定提交行为会引起很大的麻烦。我想现在你知道了。

每次我(以及许多其他开发人员也会这样说)都需要开发一些自定义行为,我使用基本的Jquery。像这样:

在您的控制器中:

public JsonResult Vote(YourModel model)
{
    // do something:
    // model.Stars

    return Json(new { message = "Success" }, JsonRequestBehavior.AllowGet);
}

你的模特:

public class YourModel
{
    // ...
    public int Stars { get; set; }
}

您的观点:

<script type="text/javascript">
    $(function () {
        $("#voteForm input[name=Stars]").change(function () {
            $.ajax({
                url: '/Home/Vote',
                type: 'GET',
                data: $("form#voteForm").serialize(),
                dataType: 'json',
                success: function (data) {
                    alert(data.message);
                },
                error: function (jq, message) {
                    alert(message);
                }
            });
        });
    });
</script>

<form id="voteForm" action="@Url.Action("Vote")">
    <input type="radio" name="Stars" value="1" checked="checked"/>
    <input type="radio" name="Stars" value="2" />
    <input type="radio" name="Stars" value="3" />
    <input type="text" name="Tbx" />
</form>

通过这种方式,您可以完全控制行为。