You can't render a partial view using only jQuery.(您不能仅使用jQuery渲染局部视图。)
You can, however, call a method (action) that will render the partial view for you and add it to the page using jQuery/AJAX.(但是,您可以调用一个方法(操作)来为您呈现局部视图,并使用jQuery / AJAX将其添加到页面中。) In the below, we have a button click handler that loads the url for the action from a data attribute on the button and fires off a GET request to replace the DIV contained in the partial view with the updated contents.(在下面,我们有一个按钮单击处理程序,它从按钮上的数据属性加载操作的url,并触发GET请求,用更新的内容替换部分视图中包含的DIV。)
$('.js-reload-details').on('click', function(evt) {
evt.preventDefault();
evt.stopPropagation();
var $detailDiv = $('#detailsDiv'),
url = $(this).data('url');
$.get(url, function(data) {
$detailDiv.replaceWith(data);
});
});
where the user controller has an action named details that does:(用户控制器具有名为详细信息的操作:)
public ActionResult Details( int id )
{
var model = ...get user from db using id...
return PartialView( "UserDetails", model );
}
This is assuming that your partial view is a container with the id detailsDiv
so that you just replace the entire thing with the contents of the result of the call.(这假设您的局部视图是具有id detailsDiv
的容器,因此您只需将整个事物替换为调用结果的内容。)
Parent View Button(父视图按钮)
<button data-url='@Url.Action("details","user", new { id = Model.ID } )'
class="js-reload-details">Reload</button>
User
is controller name and details
is action name in @Url.Action()
.(User
是控制器名称, details
是@Url.Action()
操作名称。) UserDetails partial view(UserDetails局部视图)
<div id="detailsDiv">
<!-- ...content... -->
</div>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…