vote up 0 vote down
star

When doing a Ajax call to an MVC action currently I have my javascript inside the View, not inside its own JS file.

It is then very easy to do this:

var xhr = $.ajax({
     url: '<%= Url.Action("DisplayItem","Home") %>/' + el1.siblings("input:hidden").val(),
     data: { ajax: "Y" },
     cache: false,
     success: function(response) { displayMore(response, el1, xhr) }
});

...then including the URL in the ajax call using Url.Action() inside the JS is pretty easy. How could i move this do its own JS file when without hard coding the URL?

offensive?
add comment

2 Answers:

vote up 0 vote down
check

Here's another way:

In your master page, include an area for inline scripts:

<head>
  ...
  <asp:ContentPlaceHolder runat="server" ID="_inlineScripts" />
  ...
</head>

Then in the Page_Load, create a utility function:

protected void Page_Load( object sender, EventArgs e )
{
  AddInlineScript( string.Format( "$.url=function(url){{return '{0}'+url;}}", GetBaseUri() ) );
  ...
}

private Uri GetBaseUri()
{
  var requestUrl = Request.Url.AbsoluteUri;
  var i = requestUrl.IndexOf( request.Path );

  return new Uri( requestUrl.Substring( 0, i ) );
}

private void AddInlineScript( string content )
{
  var script = new HtmlGenericControl( "script" );

  script.Attributes.Add( "type", "text/javascript" );
  script.InnerHtml = content;

  _inlineScripts.Controls.Add( script );
}

Now you can use this function in your ajax:

$.ajax({
  url: $.url('path/to/my-handler'),
  ...
});
link|offensive?
add comment
vote up 1 vote down

Wrap the AJAX call in a function that takes the URL (and any other data) as a parameter(s) and returns the response. Then in your view, call the function instead of calling the AJAX call directly.

function doAjax( url, data, elem, callback )
{
    return $.ajax({
        url: url,
        data: { ajax: data },
        cache: false,
        success: function(response) { callback(response, elem, xhr); }
    });
}

...

<input type='button' value='Go get it' onclick='doAjax( <%= Url.Action ...

I'm not sure that this is any better than having the Ajax call on the page instead of in a JS file, unless you use the exact same pattern frequently.

link|offensive?
comments (2)

Your Answer:

Get an OpenID
or

Not the answer you're looking for? Browse other questions tagged or ask your own question.