我如何使用jquery渲染部分视图?
我们可以像这样渲染局部视图:
<% Html.RenderPartial("UserDetails"); %>
我们如何使用jquery做同样的事情?
我如何使用jquery渲染部分视图?
我们可以像这样渲染局部视图:
<% Html.RenderPartial("UserDetails"); %>
我们如何使用jquery做同样的事情?
当前回答
使用标准Ajax调用实现相同的结果
$.ajax({
url: '@Url.Action("_SearchStudents")?NationalId=' + $('#NationalId').val(),
type: 'GET',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
$('#divSearchResult').html(result);
}
});
public ActionResult _SearchStudents(string NationalId)
{
//.......
return PartialView("_SearchStudents", model);
}
其他回答
@tvanfosson的答案很震撼。
然而,我建议在js中进行改进,并检查一个小的控制器。
当我们使用@Url助手调用一个动作时,我们将收到一个格式化的html。更新内容(.html)而不是实际的元素(. replacewith)会更好。
更多关于at: jQuery的replaceWith()和html()有什么区别?
$.get( '@Url.Action("details","user", new { id = Model.ID } )', function(data) {
$('#detailsDiv').html(data);
});
这在树中特别有用,因为树的内容可以多次更改。
在控制器上,我们可以根据请求者重用动作:
public ActionResult Details( int id )
{
var model = GetFooModel();
if (Request.IsAjaxRequest())
{
return PartialView( "UserDetails", model );
}
return View(model);
}
你需要在你的控制器上创建一个动作,返回“UserDetails”部分视图或控件的渲染结果。然后只需使用一个Http Get或Post从jQuery调用Action来获得呈现的html显示。
我是这样做的。
$(document).ready(function(){
$("#yourid").click(function(){
$(this).load('@Url.Action("Details")');
});
});
具体方法:
public IActionResult Details()
{
return PartialView("Your Partial View");
}
如果需要引用动态生成的值,还可以在@URL后附加查询字符串参数。动作如下:
var id = $(this).attr('id');
var value = $(this).attr('value');
$('#user_content').load('@Url.Action("UserDetails","User")?Param1=' + id + "&Param2=" + value);
public ActionResult Details( int id, string value )
{
var model = GetFooModel();
if (Request.IsAjaxRequest())
{
return PartialView( "UserDetails", model );
}
return View(model);
}
使用标准Ajax调用实现相同的结果
$.ajax({
url: '@Url.Action("_SearchStudents")?NationalId=' + $('#NationalId').val(),
type: 'GET',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
$('#divSearchResult').html(result);
}
});
public ActionResult _SearchStudents(string NationalId)
{
//.......
return PartialView("_SearchStudents", model);
}