Search code examples
javascriptasp.net-mvcclient-sideserver-side

ASP MVC 4, pass data from javascript (View) to a C# static method


I'm working on a video application and I want to trace the users' actions using the video player API (Flowplayer). I'm doing it by setting an event listener on each event to handle the "play, pause, resume, etc." events using javascript. After catching the event,I'm calling a static method placed in the server side in order to write the action to the database (and hide the tracing info from the user).

This is what I got for now:

JS Code:

<script type="text/javascript">
// bind listeners to all players on the page
flowplayer(function (api, root) {
    api.bind("pause", function () {
        console.info("pause", api.paused);

        var timePassed = api.video.time;
        @{
            Reporter.ReportPause(timePassed);
        }
        //... more code  ...

</script>

C# Code:

public static void ReportPause ( string timePassed)
{
    // do something with timePassed
}

I got an exception: "Cannot resolve symbol 'timePassed'".

How can I do it the right/elegant way (with minimal overhead).

Thank you all, YNWA


Solution

  • <script type="text/javascript">
            // bind listeners to all players on the page
            flowplayer(function (api, root) {
                api.bind("pause", function () {
                    console.info("pause", api.paused);
    
                    var timePassed = $.flowplayer().getTime();
                        $.ajax({
            url: '/Home/ReportPause',
            type: 'POST',
            dataType: "json",
            data: { timePassed: timePassed },
            error: function (a, b, c) { onError(a, b, c, parameters); },
            success: function (data) { onSuccess(data, parameters); }
        });
                    });
                }
        </script>
    
    
    // Controller
    public class HomeController{
        public JsonResult ReportPause(string timePassed)
        {
             TimePassedClass.ReportPause(timePassed);
             // more code
        }
    }
    public static class TimePassedClass
    {
          public static void ReportPause(string timePassed)
           {
              // your logic
           }
    }