Jquery 自刷新局部视图
我设置了一个小的演示应用程序,用于通过jQuery/Ajax刷新部分视图。我发现了许多从主视图刷新局部视图的示例,尽管没有从视图本身刷新局部视图的示例 这是我尝试使用的代码: 主要观点:Jquery 自刷新局部视图,jquery,ajax,asp.net-mvc,Jquery,Ajax,Asp.net Mvc,我设置了一个小的演示应用程序,用于通过jQuery/Ajax刷新部分视图。我发现了许多从主视图刷新局部视图的示例,尽管没有从视图本身刷新局部视图的示例 这是我尝试使用的代码: 主要观点: @model OrpheusTestWeb.Models.ViewModel @{ ViewBag.Title = "Home Page"; } <h2>Guid1: @Model.GUID1</h2> <div id="PartialViewDIV"> @H
@model OrpheusTestWeb.Models.ViewModel
@{
ViewBag.Title = "Home Page";
}
<h2>Guid1: @Model.GUID1</h2>
<div id="PartialViewDIV">
@Html.Partial("_PartialView", Model.GUID2)
</div>
这里出了什么问题?
提前谢谢你 为什么不返回json?
这样做:
public class PartialController : Controller
{
[HttpGet]
public JsonResult Index()
{
return Json(new { _PartialView = Guid.NewGuid().ToString()},JsonRequestBehavior.AllowGet);
}
}
<script type="text/javascript">
$("#button").on('click', function () {
$.ajax({
url: "Partial/Index",
type: "get",
dataType: "html",
success: function (result) {
var json = $.parseJSON(result);
$('#YourId').remove();
$('#PartialViewDIV').append('<div id="YourId">' + json._PartialView + '</div>');
//$("#PartialViewDIV").html(result); //the PartialViewDIV-tag is in the main view, how can i "redirect" it then?
// console.log('success', data);
}
});
});
公共类PartialController:控制器
{
[HttpGet]
公共JsonResult索引()
{
返回Json(新的{u PartialView=Guid.NewGuid().ToString()},JsonRequestBehavior.AllowGet);
}
}
$(“#按钮”)。在('单击',函数(){
$.ajax({
url:“部分/索引”,
键入:“获取”,
数据类型:“html”,
成功:功能(结果){
var json=$.parseJSON(结果);
$(“#YourId”).remove();
$('#PartialView')。追加(''+json.''u PartialView+'');
//$(“#PartialViewDIV”).html(result);//PartialViewDIV标记在主视图中,如何“重定向”它?
//console.log('success',数据);
}
});
});
您是否从中得到了一些错误或意外的结果?还有,为什么要将javascript代码放在局部视图中?这是一个非常糟糕的做法。通常情况下,javascript代码属于单独的javascript文件,不能与您的标记混合。此外,您还缺少一个结束语
)
!我把它放在同一个文件中,这样更容易阅读,不会像那样投入生产:)
public class PartialController : Controller
{
public ActionResult Index()
{
return PartialView("_PartialView", Guid.NewGuid().ToString());
}
}
public class PartialController : Controller
{
[HttpGet]
public JsonResult Index()
{
return Json(new { _PartialView = Guid.NewGuid().ToString()},JsonRequestBehavior.AllowGet);
}
}
<script type="text/javascript">
$("#button").on('click', function () {
$.ajax({
url: "Partial/Index",
type: "get",
dataType: "html",
success: function (result) {
var json = $.parseJSON(result);
$('#YourId').remove();
$('#PartialViewDIV').append('<div id="YourId">' + json._PartialView + '</div>');
//$("#PartialViewDIV").html(result); //the PartialViewDIV-tag is in the main view, how can i "redirect" it then?
// console.log('success', data);
}
});
});