最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - MVC 4 Ajax Requests - referencing a javascript file - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question asked Oct 4, 2013 at 15:35 JMBJMB 471 gold badge3 silver badges6 bronze badges 1
  • @JMB See my answer if you want to pletely write all your js code in an external file and not in your view. – KKS Commented Oct 4, 2013 at 16:04
Add a ment  | 

4 Answers 4

Reset to default 7

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,

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);
});

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>

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.

发布评论

评论列表(0)

  1. 暂无评论