How Can I pass a javascript variable value to MVC controller? -


just example:

in javascript, have 2 variable values:

  1. movie id: 2
  2. rating value: 3

i need pass values mvc controller.

for start, easiest way use ajax call jquery.

here example:

first create action this. using index starting action should create view, , view passing data movies action

 public actionresult index()     {         return view();     }      public actionresult movies(int movieid, int ratingvalue)     {         string s =  movieid + " - " + ratingvalue;          return json(s, jsonrequestbehavior.allowget);     } 

**now creating view index sending data on button click. , import jquery file , use in tag can see below **

 <html> <head> <meta name="viewport" content="width=device-width" /> <title>index</title> <script src="~/scripts/jquery-2.2.3.min.js"></script> <script type="text/javascript">     $(function () {         $('#senddata').click(function () {             var movie = 3;             var rating = 2;              var option = {                 url: '/home/movies',                 data: json.stringify({ movieid: movie, ratingvalue: rating }),                 method: 'post',                 datatype: 'json',                 contenttype: 'application/json;charset=utf-8'             };              $.ajax(option).success(function(data) {                 alert(data);             })         });     }); </script> </head> <body>     <div>          <input type="submit" value="send data" id="senddata" />     </div> </body> </html> 

and see result

result in browser


Comments

Popular posts from this blog

scala - 'wrong top statement declaration' when using slick in IntelliJ -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

PySide and Qt Properties: Connecting signals from Python to QML -