Save selection on a radiobutton asyncronously

时间:2016-04-04 17:33:25

标签: jquery asp.net-mvc asynchronous

I have a list of radio buttons that my users will use to select how someone voted. I want to save the selection when it is made asynchronously to allow for the user to continue to make selections with out having to wait for the previous selection to save.

Ideally I would eventually be able to update some indicator when the save is complete.

I have just 3 values that need to be sent to the controller the TopicID the VoterID and the SelectionValue

Is there an easy way to do this? I am thinking this should be easy but I am not having any luck making it work.

[AcceptVerbs("POST")]
    public async Task<bool>  UpdateVoteRecord(int TopicID, int VoterID, string SelectionValue )
    {

        bool retval = await Task.Run(() => helper.SaveVoteRecord(TopicID, VoterID, SelectionValue));
        return retval;
    }  

1 个答案:

答案 0 :(得分:1)

You can listen to the change event on the radio button and make an ajax call to save the selection. Assuming your rendered HTML markup looks like this

<input type="radio" name="someName" class="mySelection" value="1" />
<input type="radio" name="someOtherName" class="mySelection" value="2" />
<input type="hidden" value="100" id="TopicId" />
<input type="hidden" value="25" id="VoterId" />

Javascript

$(function(){

  $("input.mySelection").change(function(){

     var v=$(this).val();
     var url="@Url.Aciton("UpdateVoteRecord","YourController")";

     $.post(url,{ SelectionValue : v, TopicID : $("#TopicId").val(),
                                       VoterID : $("#VoterId").val() },function(res){
         //do something with res now;
        console.log(res);
      });
  });

});

I used the Url.Action helper method to generate the correct relative url to the action method. This code will work if your js code is inside a razor view. If your code is inside an external js file, Use the method explained here.

相关问题