3

Is it possible to access the javascript variable inside razor syntax?

Here is my code

       $("#add-user-to-plan").click(function () {
            var userListId = $("#user-list").val();                
            @{
                Model.Users.Add(userListId );
            }

       });

When I click the add-user-to-plan button it will add an item to a list of Users.

tereško
  • 58,060
  • 25
  • 98
  • 150
Ramppy Dumppy
  • 2,667
  • 7
  • 27
  • 37
  • 1
    possible duplicate of [Access Javascript variable in Razor code](http://stackoverflow.com/questions/9989993/access-javascript-variable-in-razor-code), [using javascript variable in MVC3 Razor view engine](https://stackoverflow.com/questions/11287484/using-javascript-variable-in-mvc3-razor-view-engine), [Pass js variable or inout value to razor](https://stackoverflow.com/questions/15991161/pass-js-variable-or-inout-value-to-razor) – dsgriffin Mar 19 '14 at 02:47

1 Answers1

5

In your Razor create a hidden field

  @Html.HiddenFor(model => model.userListId , new { id = "userListIdHidden" });

In java script assign the value for userListIdHidden

   $("#add-user-to-plan").click(function () {
        var userListId = $("#user-list").val();                
        document.getElementById("userListIdHidden").value = userListId;
   });
Golda
  • 3,823
  • 10
  • 34
  • 67