JMB
JMB

Reputation: 47

MVC 4 Ajax Requests - referencing a javascript file

Im making some ajax calls to return some partial views which are working fine when the scripts are written in the view.

Script code is

<script type="text/javascript">
$.ajax({
    url: "@(Url.Action("ProjectPartial", "Project"))",
    contentType: 'application/html; charset=utf-8',
    type: 'POST',
    dataType: 'html',
    data: {
        documentType: $('#DocumentType').val(),
        sectionName: $('#SectionName').val()
    }
})
.success(function (result) {
// Display the section contents.
$('#Projects').html(result);
})
.error(function (xhr, status) {
alert(xhr.responseText);
});
</script>

What i want to do is to store these in a javascript file called renderpartial.js so that i can add ajax calls to to one file and not write them into every view.

Does anyone know if this is possible?

Ive tried putting

<script src="~/Scripts/RenderPartial.js"></script>

at the top of my page but all i get is the error function.

Upvotes: 1

Views: 3006

Answers (4)

pwdst
pwdst

Reputation: 13735

A pattern I have used on recent projects to avoid polluting the global namespace is to encapuslate the function and configuration variables into an object-

var projectHelpers {
   config: {
       projectUrl: null
   },
   init: function() {
      //Do any page setup here...
   },
   getPartial: function() {
   if (projectHelpers.config.projectUrl) {
         $.ajax({   
            url: projectHelpers.config.projectUrl,
            contentType: 'application/html; charset=utf-8',
            type: 'POST',
            dataType: 'html',
            data: {
                documentType: $('#DocumentType').val(),
                sectionName: $('#SectionName').val()
            },
            error: function (xhr, status) {
            alert(xhr.responseText); //Consider if console.log is more appropriate here
            },
            success: function (result) {    
                $('#Projects').html(result); // Display the section contents.
            }});
        } else {
            console.log("Missing project URL);
        }
   }
};

And then in the page-

projectHelpers.config.projectUrl = "@(Url.Action("ProjectPartial", "Project"))";
projectHelpers.init();

This helps encapsulate your code and is particularly useful when working with lots of external libraries to avoid variable collisions, as well as avoiding coding errors where you re-use a variable name and overwrite values.

See What does it mean global namespace would be polluted? and Using Objects to Organize Your Code.

Upvotes: 0

KKS
KKS

Reputation: 3630

There are two ways to do it:

  1. By using AJAX.BeginForm. Using this, helps you not to write your javascript/jquery ajax calls but it is useful when you are doing something with only one form. When your form renders it then creates javascript for you which makes your view very clean.
  2. I normally use a html5's data- attribute to read such kind of data that is easily available from the view in my js files. Because there are many cases where you want something to read from server in your view and you also want that data to be accessed in your javascript code, mainly in another view. Use razor syntac to put data in data- attributes like this:

    //I assume you write this attribute in any control like this

    data-url="@(Url.Action("ProjectPartial", "Project")"

    //or if you want to write it in any html helper control as html attribute like this

    new { data_url="@(Url.Action("ProjectPartial", "Project")"}

Now in your external js file you can read the url while making an ajax call. You can write as many data attributes as per your needs and make your of razor syntax to give you your data eg: type-post/get, contenttype,etc. and use like this:

$.ajax({
    url: $('anyinput').attr('data-url');,
    contentType: 'application/html; charset=utf-8',
    type: 'POST',
    dataType: 'html',
    data: {
        documentType: $('#DocumentType').val(),
        sectionName: $('#SectionName').val()
    }
})
.success(function (result) {
// Display the section contents.
$('#Projects').html(result);
})
.error(function (xhr, status) {
alert(xhr.responseText);
});

Upvotes: 2

Oxon
Oxon

Reputation: 5041

How about move the following to the js file.

function getPartial(UrlToGet) {
    $.ajax({
        url: UrlToGet,
        contentType: 'application/html; charset=utf-8',
        type: 'POST',
        dataType: 'html',
        data: {
            documentType: $('#DocumentType').val(),
            sectionName: $('#SectionName').val()
        }
    })
    .success(function (result) {
        // Display the section contents.
        $('#Projects').html(result);
    })
    .error(function (xhr, status) {
        alert(xhr.responseText);
    });
}

And in your view:

<script type="text/javascript">
$(function () {
    getPartial('@(Url.Action("ProjectPartial", "Project"))');
});
</script>

Upvotes: 0

Murali Murugesan
Murali Murugesan

Reputation: 22619

As long as you use inline razor syntax like @(Url.Action( you can't move it to js file

You can do it in either specifying url like

url: '/Project/ProjectPartial',

or in View.cshtml

<script type="text/javascript">
var projectUrl="@(Url.Action("ProjectPartial", "Project"))"
</script>

in RenderParial.js

url: projectUrl,

Upvotes: 7

Related Questions