开发者

What's the best way of getting Id from Url with asp.net mvc

I'm new to Jquery and Asp.Net MVC. i am trying to pass an ID parameter

from an ActionLink on a page to jQuery function. This Id is then passed to a controller that returns a resultset that is rendered in a modal dialog box.

what is the best way of capturing the Id parameter from the ActionLink in the Jquery Function? Note there are several action links with different Ids assigned to them.

this is my action link below:

<%=Html.ActionLink("View", "GetDetailsById", new { id = x.ProductId }, new { @class = "view",@productId= x.ProductId })%>

this below is my jquery function.

       $(function () {
             var _id;


             $(".view").click(function () {
                 // Get the ID value of this button.

                 _id = $(this).attr('productId');                    

                 // Initialize the dialog and call the next function
                 // to get the data.                  
                 $("#dialog-message").dialog('open');

                return false;
             });

Note i got this to work by adding a custom attribute to actionlink -@productId. I then grab the value using jquery like this:

$(".view").click(function () { // Get the ID value of this button.

                 _id = $(this).attr('productId');               

This Id is passed to a jquery function that calls a method in the controller.

Is this a good way of getting the Id, or is there a开发者_JAVA技巧 cleaner way of doing this?

regards

Kojo


You could assign the productId to the Id of the html element generated, by specifying an id in the html attributes parameter:

new { @class = "view", id = x.ProductId }

Then, instead of using a productId attribute, you could grab the id of the generated <a> tag in the same way, that is use $(this).attr("id").

I would recommend this over using productId since id is valid HTML.

So, your code would end up looking like this:

<%=Html.ActionLink("View", "GetDetailsById", new { id = x.ProductId }, new { @class = "view", id = x.ProductId })%>

which would generate an <a> with id of productId. Then your jQuery would look like this:

       $(function () {
         var _id;


         $(".view").click(function () {
             // Get the ID value of this button.

             _id = $(this).attr('id');                    

             // Initialize the dialog and call the next function
             // to get the data.                  
             $("#dialog-message").dialog('open');

            return false;
         });


I would pass the id to the view model then insert the value in a javascript variable manually

<script type="text/javascript">
     var id = '<% ViewData["theid"] %>';
</script>

This is the same technique stackoverflow uses in their code. Go ahead and look at their html and you will see.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜