Search code examples
asp.net-mvchtml.actionlinkurl.action

How to format action link pass parameter in mvc?


I have a trouble with action link as text in mvc .

  function ListProduct() {
            $.get('@Url.Action("ListProduct", "Product")')
                 .done(function (data) {
                     var json = JSON.parse(data.result);
                     $.each(json, function (idx, obj) {
                        $("#tb_product tbody").append(
                        '<tr>' +
                        ' <td>' + obj.CATEGORY_NAME + '</td>' +
                        ' <td><a href="@Url.Action("Detail", "Product", new { id = '+ obj.PRODUCT_ID + ' })">' + obj.PRODUCT_NAME + '</a></td>' +' </tr>');
                        });
                    });
        }

But seem it's not working, it's get error too many charaters in character literal at '+ obj.PRODUCT_ID + ' . Thank you see it.


Solution

  • Razor code (@Url.Action(...)) runs server-side, while JavaScript runs client-side, long after the server has already done it's work, returned a response, and moved on to other things. As a result, you can't pass a JavaScript variable into a Razor method, as that JavaScript variable doesn't even exist as a thing yet.

    If you need to include the value as part of the actual URL path, then you can perhaps construct the path manually. For example:

    '<a href="@Url.Action("Detail", "Product")'+ obj.PRODUCT_ID + '">' + obj.PRODUCT_NAME + '</a>'
    

    In other words, server-side, @Url.Action("Detail", "Product") is evaluated an returns something like /product/detail/. Then, client-side, in your JavaScript, all you're doing is just concatenating the product id onto this existing string, resulting in something like /product/detail/xxxxxx.