简体   繁体   中英

MVC equivalent of @Html.ActionLink through javascript

如何通过javascript代码编写等效的@ Html.ActionLink,即调用MVC操作,然后创建一个新视图而不返回调用视图?

javascript is a client side language which doesn't know anything about the server side language you are using. Thus it is normal that there's no equivalent in javascript of the server side helper that generates an url using your server side route definitions.

It is not quite clear what you are trying to achieve but if you want to use call some url through javascript you could generate this url using a server side helper:

<script type="text/javascript">
    var url = '@Url.Action("SomeAction", "SomeController")';
    // do something with the url client side variable, for example redirect
    window.location.href = url;
</script>

If you want to use this url in a separate javascript file where you don't have access to server side helpers you could still, depending on the situation, include this url in some DOM element.

For example:

<div id="foo" data-url="@Url.Action("SomeAction", "SomeController")">Click me</div>

Notice the data-url HTML5 attribute that we have embedded into the DOM and used a server side helper to ensure that the generated url will always be correct based on our routing definitions. Now we could in a separate javascript file unobtrusively subscribe to the click event of this div and retrieve the url:

$('#foo').click(function() {
    var url = $(this).data('url');
    // do something with the url client side variable, for example redirect
    window.location.href = url;
});

Other examples obviously include the standard <a> and <form> elements which should be generated using server side HTML helpers and then all you have to do in your separate javascript file is to fetch their corresponding href or action attributes to retrieve the actual url and do something with it.

Another option is to store the URL in a hidden <div> somewhere on your page and call it via Javascript later. It would look like this:

Index.cshtml :

<div style="display: none;" id="url">
   @Url.Action("SomeAction", "SomeController")
</div>

Then you can use this in your Script.js file to build any links you want.

var url = $("#url").text();

The URL variable would then contain a websafe link to /SomeController/SomeAction .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM