2

I'm trying to generate a link using following

$(this).parent().attr('href', '@Url.Action("Create", "Home"' + '?clientId=' + clientId + '&clientName=' + clientName);

somewhere I read that I need to isolate this Url.Action with controller and action into variable so I tried with this

var a = '@Url.Action("Create", "Home"';
$(this).parent().attr('href', a + '?clientId=' + clientId + '&clientName=' + clientName);

But this still doesn't work. In browser I'm getting

http://localhost:1328/Home/Index2/@Url.Action%28%22Create%22,%20%22Home%22?clientId=181&clientName=undefined

2
  • 3
    That would mean that you script is in an external file - Razor code is not parsed n external files. You would need to create the base url in the main view (either a global variable or pass its value to your function) Commented Mar 17, 2016 at 7:49
  • can you please provide with example. Commented Mar 17, 2016 at 7:49

2 Answers 2

2

Another option is to store the url with data-* attributes and access them. In the View you can add the below attribute:

data-url='@Url.Action("Create", "Home")'

Now you can access this in the script with:

var base = $(this).data('url');
$(this).parent().attr('href', base + '?clientId='+ clientId +'&clientName=' + clientName);
Sign up to request clarification or add additional context in comments.

Comments

1

Your script should be on Razor page in order to make @Url.Action helper work.

When you place it there this should work:

//this line should generate /Home/Create string
var urlNoParam = '@Url.Action("Create", "Home")';
//and here you just add params as you want
$(this).parent().attr('href', urlNoParam  + '?clientId=' + clientId + '&clientName=' + clientName);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.