Search code examples
javascriptc#jqueryasp.net-mvcasp.net-mvc-routing

Routing don't work as expected


I have the following route definition:

routes.MapRoute(
                "FormPreview",
                "Forhandsgranska/{FormId}/{action}/{id}",
                new { controller = "FormPreview", action = "Introduction", id = UrlParameter.Optional }
                );

I have the following code that triggers the route and It works perfect:

  $('#previewButton').on('click', function(){
                document.location = '@Url.Action("","formPreview", new { formId = Model.Id })';
            });

But now I have the following code that don't work. My route definition is not triggered and I'm redirected to a wrong page, and I don't know why:

var formId = $(this).closest('tr').data('formId');
                        document.location = "@Url.Action("", "formPreview")/" + formId;

What Is the difference between these two? Why Is the first one working and not the second one?


Solution

  • You have to use .replace method.

    document.location = '@Url.Action("", "formPreview",new {formId ="formId"})'.replace("formId",formId);
    

    In Razor every content using a @ block is automatically HTML encoded by Razor.