How should I handle Asp.net MVC URLs in javascript calls?

I am trying to write the javascript heavy part of my Asp.net MVC web application (this part of the website is an RIA using Extjs). However, I settled on the right way to handle URLs in javascript.

For example, right now I have an Ajax call for an action Listin ObjectsControllerthat is in scope Reading. The List action takes an documentId(int) parameter . At the moment, this compares to /Reading/Objects/List, since I have not changed the routing yet (the site is too young at the time the routes were completed). Usually in a view, to put this URL in a string, I would do @Html.Action("List", "Objects", new { area = "Reading", documentId = 3).

However, this does not work when working with javascript, since javascript is not parsed by viewview.

To get around this, I have a very small view that returns javascript constants, such as URLs, which are loaded before my main application js files. The problem is that I cannot call Html.Actionfor this action, because with a constant creation time I (obviously) do not know what documentId ajax calls will be, and if you exclude documentIdfrom the call, Html.Actionan exception is raised. DocumentId may change during normal application workflow.

How can I handle this? I don’t want to hardcode the URL /Reading/Objects/List, because if I change my routing for this (for a more convenient json API), or this web application is not located in the root of the domain, the URL will not be more durable.

How do everyone else handle MVC urls in their javascript calls?

+5
3

, . , JavaScript :

<script>
var url = '@Url.Action("List", "Objects", new { area = "Reading", documentId = "_documentId_")';
var id = 100;
var finalUrl = url.replace('_documentId_', id);
</script>

"_documentId_" . JavaScript "_documentId_" id, , . , , , URL- .


: 20

. , JavaScript intellisense VisualStudio.

http://weblogs.asp.net/zowens/archive/2010/12/20/asp-net-mvc-javascript-routing.aspx

+6

javascript javascript. AJAX :

@Html.ActionLink("click me", "List", "Objects", 
    new { area = "Reading", documentId = 3 }, new { id = "foo" })

js onclick ( jquery):

$(function() {
    $('#foo').click(function() {
        $('#resultDiv').load(this.href);
        return false;    
    });
});

, - javascript. URL- html-.

<form>, onsubmit ( ) action URL-.


UPDATE:

, documentId , :

@Html.ActionLink("click me", "List", "Objects", 
    new { area = "Reading" }, new { id = "foo" })

:

$(function() {
    $('#foo').click(function() {
        $('#resultDiv').load(this.href, { documentId: '123' });
        return false;    
    });
});
+2

It turns out that all this was solved using Url.Action()instead Html.Action(). Url.Action()(so far) allows me to generate URLS without any parameters. I assume this only works when the route does not specify parameters in the destination URL.

0
source

All Articles