2012-08-14 15 views
0

我想把我的JS移动到一个单独的文件,而不是直接在页面上。但是,由于某种原因,我无法正常工作。JavaScript不能从单独的文件工作

我想根据下拉选择来更新网站。现在我在做它的方式是这样的:

查看:

<script type="text/javascript"> 
$(document).ready(function() { 
    $("#EntityType").change(function() { 
     /* Get the selected value of dropdownlist */ 
     var selectedID = $(this).val(); 

     /* Request the partial view with .get request. */ 
     $.get('/Entity/Create_DropDownList/' + selectedID, function (data) { 

      /* data is the pure html returned from action method, load it to your page */ 
      $('#entity_form_attributes').html(data); 
      /* little fade in effect */ 
      $('#entity_form_attributes').fadeIn('fast'); 
     }); 
    }); 
}); 
</script> 

    <div class="editor-field"> 
     @Html.DropDownList("EntityType", (SelectList)ViewData["Types"]) 
    </div> 

    <div id="entity_form_attributes"></div> 

这是工作。应该将部分视图加载到div标记中。 但是,如果创建一个JavaScript文件,然后将脚本移动到文件中,它将失败。 从共享的开始网站我包括JavaScript文件。

任何人都可以看到我做错了什么。该应用程序是一个MVC3应用程序。是否有设置/财产我必须设置使这项工作?

回答

1

任何人都可以看到我做错了什么。

是的,你已经硬编码的网址在这里,而不是使用Url助手来生成它。你永远不应该这样做:

$.get('/Entity/Create_DropDownList/' 

当你在IIS中部署你的应用程序,因为你的url是错误的,这会中断。由于这个硬编码的网址,您在开始时省略了虚拟目录名称。

因此,在处理ASP.NET MVC应用程序中的URL时,总是使用Url助手。所以你的情况,你可以生成的网址,该视图作为HTML5 data-*属性:

@Html.DropDownList(
    "EntityType", 
    (SelectList)ViewData["Types"], 
    new { data_url = Url.Action("Create_DropDownList", "Entity") } 
) 

,然后在单独的JavaScript文件,只检索这个网址,并使用它:

$("#EntityType").change(function() { 
    /* Get the selected value of dropdownlist */ 
    var selectedID = $(this).val(); 

    /* Get the url from the data-url HTML attribute */ 
    var url = $(this).data('url'); 

    /* Request the partial view with .get request. */ 
    $.get(url, { id: selectedID }, function (data) { 
     /* data is the pure html returned from action method, load it to your page */ 
     $('#entity_form_attributes').html(data); 
     /* little fade in effect */ 
     $('#entity_form_attributes').fadeIn('fast'); 
    }); 
}); 
+0

确定。我看到。但是应用程序正在运行,直接在视图中使用jscript。改变了,你指出了什么,并将jscript移动到seperat文件,仍然没有奏效。 – 2012-08-14 09:25:24

+2

请定义*不起作用*。你有错误吗?你在FireBug中看到什么?是否正在执行AJAX请求...?请求的样子是怎样的?服务器的响应是什么样的?脚本是否正确包含(使用Url助手而不是硬编码它的位置)?你在FireBug的Net标签中看到了什么?任何404? – 2012-08-14 09:28:29

+0

不工作=静态内容。该网站没有更新,当我从下拉列表中选择一个项目。 – 2012-08-14 11:32:58

相关问题