Bryan
Bryan

Reputation: 3541

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?

Upvotes: 0

Views: 58

Answers (2)

NightOwl888
NightOwl888

Reputation: 56869

What you have specified: @Url.Action("", "formPreview"), is not the same as @Url.Action("","formPreview", new { formId = Model.Id }). It doesn't match because in the route table you have a required formId, but you haven't specified it in @Url.Action.

Since your URL generated by routing happens before the JavaScript has a chance to interact with it, I suppose one (hacky) way to do it would be to create a dummy formId value and replace it on the client side with a real value.

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

Alternative

Or you could add the dummy as a default value when the formId is not supplied.

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

Then you could replace the value on the client when needed.

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

However, as a side effect that means whenever you create a URL without specifying the FormId it will come out as /Forhandsgranska/DUMMY.

Upvotes: 1

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48367

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.

Upvotes: 1

Related Questions