[英]Refactor jQuery AJAX call for partial view
In my ASP.net MVC 5 application, I have lots of call to different partial views. 在我的ASP.net MVC 5应用程序中,我多次调用不同的局部视图。 To load/refresh those view, I am using jQuery AJAX. 要加载/刷新这些视图,我正在使用jQuery AJAX。
However I ended up having lot of call to jquery which seems ugly and redundant. 但是我最终对jquery进行了很多调用,这看起来很丑陋且多余。 I am thinking there must be a better way to do this. 我认为必须有更好的方法来做到这一点。
Here is my script in my index.cshtml
where I am calling partial views. 这是我的index.cshtml
中的脚本,我在其中调用部分视图。
$(document).ready(function() {
// load today's level
$.ajax({
url: '@Url.Action("_TodayLevel")',
type: 'GET',
contentType: 'application/json',
dataType: 'html',
//traditional: true,
}).success(function(e) {
$('#today-level').html(e);
});
// .... truncated to save space. But you get the idea, I have lots of this
// load host level
$.ajax({
url: '@Url.Action("_HostLevel")',
type: 'GET',
contentType: 'application/json',
dataType: 'html',
//traditional: true,
}).success(function (e) {
$('#host-level').html(e);
});
});
Is there any better way to do this? 有什么更好的方法吗?
In the examples you gave, you are essentially requesting an HTML page and then updating a portion of the page with the returned HTML. 在您给出的示例中,您实际上是在请求一个HTML页面,然后使用返回的HTML更新页面的一部分。
If this is the case, then you can simply use jQuery's .load()
method: https://api.jquery.com/load/ 如果是这种情况,那么您可以简单地使用jQuery的.load()
方法: https : //api.jquery.com/load/
You may simply consider to use below code to achieve what you want 您可能只是考虑使用以下代码来实现所需的功能
@{Html.renderaction("_TodayLevel","Controller");}
If you does not have any controller action for this two views you may also consider to use 如果您对这两个视图没有任何控制器操作,则也可以考虑使用
@{Html.renderPartial("_yourViews");}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.