Postback on RadioButtonFor in MVC

11.2k views Asked by At

I have 2 radio buttons in my mvc webpage.

 <% using (Html.BeginForm("Search", "Search"))
   { %>
  // some html codes
     <%= Html.RadioButtonFor(m => m.Agents, "A", new { Checked = "checked" })%> //radio button 1                     
      <%= Html.RadioButtonFor(m=> m.Agents,"AG") %>  //radio button 2                      
  // some html codes
   <% } %>

the aspx page is shown below.

I also have button in my page.and if i clicked on that button,then there is a postback occures.

I need another postback if i changed radiobutton selection. How can i make postback on that event.But there is no postback if i changed the selection of radio buttons. How can i achieve this?

2

There are 2 answers

0
Darin Dimitrov On BEST ANSWER

You will need to use javascript for this. There is no server side event occurring when the user changes the selection of a radio button. So if you are using jquery you could subscribe for the .change() event and submit the form:

<% using (Html.BeginForm("Search", "Search", FormMethod.Post, new { id = "myform" })) { %>
    <%= Html.RadioButtonFor(m => m.Agents, "A", new { @checked = "checked", @class = "radio" }) %>
    <%= Html.RadioButtonFor(m => m.Agents, "AG", new { @class = "radio" }) %>
<% } %>

and then in a separate javascript file:

$(function() {
    $('#myform .radio').change(function() {
        $('#myform').submit();
    });
});
0
Murtaza H On

this is one way of doing post back with radio button:

<label>@Html.RadioButton("Buyer", "Buyer", new { onchange = "this.form.submit();" })Buyer</label>