简体   繁体   中英

Pass data from JavaScript function as an object parameter to @Html.Action() C#

Here is what I am trying to do. I want to be able to call an html action and pass in some data as an object parameter. The only thing is this data needs to be returned from a javascript function.

Here is what I am trying to do:

 @Html.Action("someAction", "someController", new { passedData = GetDropDownData() }) <script> function GetDropDownData() { var data = "test"; return data; } </script> 

Basically I am trying to pass some drop down data from a control to a partial view being rendered with the @Html.Action(). I want to be able to pass this string to the partial view somehow so I figured I could use JS to pull the drop down data and return it as an object parameter when rendering the page?

Let me know if you have any suggestions or a better way to go about this.

Thank you!

This is not possible the way you're doing it, because razor views are compiled on server side, while javascript is client side. Therefore, the views are already compiled, while javascript runs during runtime. One way to do it is to use ajax to pass variables from javascript to an action in the controller as query parameters or body values. You could achieve that by creating a button or link:

<a href='#' id='clickMe'>Click me</a>

And hooking up jQuery to do the job:

<script>
$(document).ready(function(){

   $('#clickMe').click(function(){

      $.ajax({
         type: "POST",
         url: '@Url.Action("Action", "Controller")',
         data: {
            passedData: GetDropDownData()
         },
         success: function(response){
             $('#placeholderForPartialView').html(response);
         }
      });
   });
});
</script>

It would look something like this depending on your method (GET or POST) type. Here I assume that you return Partial view as a result and replace the contents of #placeholderForPartialView div with the returned view. Please correct me if I'm wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM