jQuery 如何通过对控制器的ajax调用在MVC5中呈现部分视图并返回HTML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32610270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:54:16  来源:igfitidea点击:

How to render partial view in MVC5 via ajax call to a controller and return HTML

jqueryhtmlajaxasp.net-mvcasp.net-mvc-partialview

提问by Paceman

How can use AJAX to load a complete partial view rendered in html (so I just set the div.html)

如何使用 AJAX 加载以 html 呈现的完整部分视图(所以我只是设置了 div.html)

I need the ajax call to call controller action that will render a complete partial view (red) and append it at the end of the currently loaded one?

我需要 ajax 调用来调用控制器操作,该操作将呈现完整的局部视图(红色)并将其附加到当前加载的视图的末尾?

[I know how to append to DOM and how to make AJAX calls]

[我知道如何附加到 DOM 以及如何进行 AJAX 调用]

I need to know what is the best plumbingapproach for this, what type of ActionResult should the action returnand if there is an already built-in mechanism for thisso to avoid reinventing the wheel?

我需要知道什么是最好的管道方法,动作应该返回什么类型的 ActionResult以及是否有一个已经内置的机制以避免重新发明轮子?

enter image description here

在此处输入图片说明

回答by Viktor Bahtev

There is built-in ajax helpers in ASP.NET MVC which can cover the basic scenarios.

ASP.NET MVC 中内置了 ajax 助手,可以覆盖基本场景。

You need to install and refer jquery.unobtrusive-ajaxJavaScript library ( + jQuery dependency). Then in your main view (let's say index.cshtml) put following code:

您需要安装并引用jquery.unobtrusive-ajaxJavaScript 库(+ jQuery 依赖项)。然后在您的主视图(假设 index.cshtml)中输入以下代码:

Index.cshtml

索引.cshtml

@Ajax.ActionLink("Load More Posts", "MorePosts", new AjaxOptions()
{
    HttpMethod = "GET",
    AllowCache = false,
    InsertionMode = InsertionMode.InsertAfter,
    UpdateTargetId = "posts-wrapper"
})

<div id="posts-wrapper"></div>

Note: @Ajax.ActionLinkhelper accepts AjaxOptionsparameter for more customizations.

注意@Ajax.ActionLinkhelper 接受AjaxOptions参数以进行更多自定义。

In the controller (let's say HomeController.cs) you should return PartialViewResult:

在控制器(假设HomeController.cs)中,您应该返回PartialViewResult

public ActionResult MorePosts(int? offset, int? count)
{
    IEnumerable<Post> posts = myService.GetNextPosts(offset, count); 
    return PartialView(posts);
}

Finally you define the MorePosts.cshtmlpartial view:

最后定义MorePosts.cshtml部分视图:

@model IEnumerable<Post>

@{
    Layout = null;
}

@foreach (var post in Model)
{
    <div class="post">
        <div>>@post.Prop1</div>
        <div>@post.Prop2</div>
    </div>
    <hr />
}

And that's it. When some user clicks on Load Morebutton, more posts will be loaded.

就是这样。当某些用户单击Load More按钮时,将加载更多帖子。

Note 1: you can implement OnBeginfunction to implement the actual logic for deciding which are the next posts to load (ex. get the id of the last loaded post and send it to the server).

注意 1:您可以实现OnBegin函数来实现决定哪些是下一个要加载的帖子的实际逻辑(例如,获取上次加载的帖子的 id 并将其发送到服务器)。

Note 2: the same result can be achieved with custom jQuery.ajaxcalls (without jquery.unobtrusive). The only differences will be the manual ajax calls and click events.

注 2:使用自定义jQuery.ajax调用(没有 jquery.unobtrusive)可以实现相同的结果。唯一的区别是手动 ajax 调用和点击事件。



Hope this helps. I can write a more complete example if needed.

希望这可以帮助。如果需要,我可以写一个更完整的例子。

回答by Luke

I recommend getting the Westwind.Web.Mvclibrary from NUGET and you can run any of your views to a string to return back as a JSON result

我建议Westwind.Web.Mvc从 NUGET获取库,您可以将任何视图运行到字符串以作为 JSON 结果返回

public JsonResult GetPosts()
{
    string postsHtml = ViewRenderer.RenderPartialView("~/views/yourcontroller/_PostsPartial.cshtml",model);

    return Json(new { html = postsHtml });
}

As @Guruprasad said in the comments, you can simply return back a partial view from an MVC controller using return PartialView(model), but with the RenderPartialView you get it as a string that you can output as JSON along with any other values if required. This will work if you choose to use WebAPI, because it doesn't have the ability to render a view built in.

正如@Guruprasad 在评论中所说,您可以使用 简单地从 MVC 控制器返回部分视图return PartialView(model),但使用 RenderPartialView 将其作为字符串获取,如果需要,您可以将其与任何其他值一起输出为 JSON。如果您选择使用 WebAPI,这将起作用,因为它无法呈现内置视图。