按单选按钮调用操作方法

时间:2016-04-18 08:27:48

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

我有3个单选按钮。我想要这样的逻辑:当我按下单选按钮时 将调用所需的操作方法。我不知道如何使用它 JQuery的。还有其他任何变种吗?

<h3>Gender:</h3>

    @Html.RadioButton("Gender", "All", true, new {id = "radioAll"})
    @Html.Label("All")

<br/>

    @Html.RadioButton("Gender", "Male", false, new {id = "radioMale"})
    @Html.Label("Male")

<br/>
@Html.RadioButton("Gender", "Female", false, new {id = "radioFemale"})
@Html.Label("Female")

// I tried to find out a decision but couldn't.
<script>
    $(document).ready(function () {
    var url = '@Url.Action("ShowUsers", "Home")';

    if ($("#radioMale").attr("checked") === "checked") {
        $.post(url, 'choice=' + "Male");
    }
});
</script>

3 个答案:

答案 0 :(得分:0)

试试这个:为名单=&#39;性别&#39;的单选按钮注册一个点击处理程序并将单击的单选按钮值传递给url。

$(document).ready(function () {
    var url = '@Url.Action("ShowUsers", "Home")';

    $("input:radio[name='Gender']").on("click",function(){
        var choice = $(this).val();
        $.post(url, {'choice':choice});// data must be passed as key value pair
    });
});

<强> More Information for $.post()

答案 1 :(得分:0)

使用如下:

$(document).ready(function() {
    $('input[type=radio][name=Gender]').change(function() {
        if (this.value == 'Male') {
            $.post( '@Url.Action("ShowUsers", "Home", new {choice = "Male"})', function( data ) {
               //do something
            });

        }
        else if (this.value == 'Female') {
            $.post( '@Url.Action("ShowUsers", "Home", new {choice = "Female"})', function( data ) {
               //do something
            });
        }
        else{
            $.post( '@Url.Action("ShowUsers", "Home")', function( data ) {
               //do something
            });
        }
    });
});

答案 2 :(得分:0)

您的代码似乎就是: 加载文档后,检查#radioMale的值。 如果选中它(刚加载文档时),请执行操作。

您可能想要在单选按钮上设置一个监听器,当它们被单击时,您就可以调用您的操作。

以下示例: VIEW

<div>
@Html.RadioButton("male", "male", new { id = "male" });
@Html.RadioButton("female", "female", new { id = "female" });
</div>
@section scripts{ 
<script>
    var baseUrl = '@Url.Action("ShowUsers", "Home")';
    $(document).ready(function(){
        $("#male").click(function (e) {
            $.get(baseUrl, { choice: e.target.id }, function (data) {
                console.log(data);
            });
        });
        $("#female").click(function (e) {
            $.get(baseUrl, { choice: e.target.id }, function (data) {
                console.log(data);
            });
        }); 
    });
</script>

}

ACTION

public ActionResult ShowUsers(string choice)
{
    return View();
}