1

I must call this javascript function from inside a view:

$("#addCompositionItem").click(function (carrier) {
        $.mobile.loading('show');
        $.ajax({
            url: this.href,
            cache: false,
            success: function (html) {
                $("#Compositions"+carrier).append(html);
                $("#newServicePageContent").trigger("create");
                $.mobile.loading('hide');
            }
        });

        return false;
    });

As you can see, carrier is a parameter used to load html portions in different containers. How can I pass this value from an action link? I'm trying with:

@Html.ActionLink("Text", "ActionName", "ControllerName", new { id = "addCompositionItem", carrier="XYZ",type = "submit" })

but with no success

2 Answers2

1

The way I understand what's happening is that you're using the HTML Helper to generate an anchor tag and then attaching via JavaScript to handle the click event. In your handler, you want to be able to get a piece of data from the original link.

My suggestion is to use HTML data annotations to hold the data. As you have it now, your parameters are just being encoded into the href attribute via the route parameters. If you instead move it to the html attributes and use data_carrier the framework will generate your anchor tag like the following (not the underscore-to-hyphen is automatic conversion):

@Html.ActionLink("Text", "ActionName", "ControllerName", new { /*route params*/}, new { data_carrier="..." })

Should result in something like:

<a href='...' data-carrier='...'>...</a>

Then in your JavaScript, instead of trying to get the value as a parameter, simply use the jQuery data() method or any raw JavaScript you like to access the attribute.

var carrier = $(this).data('carrier');

I think this will cover your use case.

Erik Noren
  • 4,279
  • 1
  • 23
  • 29
0

The code snippet below was given by EndangeredMassa in this SO question. It should solve your problem.

<html>
<head>
<script type="text/javascript">

    // Wait for the page to load first
    window.onload = function() {

      //Get a reference to the link on the page
      // with an id of "mylink"
      var a = document.getElementById("mylink");

      //Set code to run when the link is clicked
      // by assigning a function to "onclick"
      a.onclick = function() {

        // Your code here...

        //If you don't want the link to actually 
        // redirect the browser to another page,
        // "google.com" in our example here, then
        // return false at the end of this block.
        // Note that this also prevents event bubbling,
        // which is probably what we want here, but won't 
        // always be the case.
        return false;
      }
    }
</script>
</head>
<body>
    <a id="mylink" href="http://www.google.com">linky</a>        
</body>
</html>
Community
  • 1
  • 1
VtoCorleone
  • 16,813
  • 5
  • 37
  • 51