2016-04-18 56 views
1

我有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> 

回答

0

試試這個:爲名稱='性別'的單選按鈕註冊一個單擊處理程序,並將單擊的單選按鈕值傳遞給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()

+0

什麼樣的行動必須調用方法?獲取或發佈? –

+0

'$ .post'僅適用於POST方法。但數據應該像關鍵值pari'{choice:choice}',參見[this](http://api.jquery.com/jquery.post/)表單更多信息 –

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 
      }); 
     } 
    }); 
}); 
0

看來,如果你說你的代碼是什麼: 當文件已加載,檢查的價值#radioMale。 如果選中(當文檔剛加載時),POST發送到您的操作。

您可能想要在單選按鈕上設置偵聽器,並在單擊它們時調用您的操作。下面

例子: 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(); 
}