在ASP.NET MVC中使用jQuery渲染局部视图

Pra*_*sad 220 javascript asp.net-mvc jquery renderpartial

如何使用jquery渲染局部视图?

我们可以像这样渲染局部视图:

<% Html.RenderPartial("UserDetails"); %>
Run Code Online (Sandbox Code Playgroud)

我们如何使用jquery做同样的事情?

tva*_*son 284

您不能仅使用jQuery渲染局部视图.但是,您可以调用一个方法(操作)来为您呈现局部视图,并使用jQuery/AJAX将其添加到页面中.在下面,我们有一个按钮单击处理程序,它从按钮上的数据属性加载操作的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);         
    });
});
Run Code Online (Sandbox Code Playgroud)

用户控制器具有名为详细信息的操作:

public ActionResult Details( int id )
{
    var model = ...get user from db using id...

    return PartialView( "UserDetails", model );
}
Run Code Online (Sandbox Code Playgroud)

这假设你的局部视图是一个带有id的容器,detailsDiv这样你就可以用调用结果的内容替换整个东西.

父视图按钮

 <button data-url='@Url.Action("details","user", new { id = Model.ID } )'
         class="js-reload-details">Reload</button>
Run Code Online (Sandbox Code Playgroud)

UserDetails局部视图

<div id="detailsDiv">
    <!-- ...content... -->
</div>
Run Code Online (Sandbox Code Playgroud)


Pra*_*sad 150

我使用ajax加载来执行此操作:

$('#user_content').load('@Url.Action("UserDetails","User")');
Run Code Online (Sandbox Code Playgroud)

  • 一般来说,我认为你最好使用Url.Action助手,而不是硬编码路径.如果您的网站位于子目录而不是根目录中,这将会中断.使用帮助程序可以修复该问题,并允许您使用动态设置的值添加参数. (46认同)
  • 您可以执行$('#user_content').load('@ Url.Content("〜/ User/UserDetails")')来解决这个问题 - 如果我需要javascript来查询查询字符串参数,我会经常使用此方法在网址的末尾 (18认同)
  • @Prasad:**Urls**应始终使用`@ Url.Action("ActionName","ControllerName",new {area ="AreaName"})来评估,而不是使用**Handcoding**. (4认同)
  • @PKKG.@ Url.Action()仅在Razor中进行评估.如果OP希望将其代码放在单独的js文件中并引用它,则不起作用. (3认同)

Cus*_*dio 60

@tvanfosson摇滚着他的回答.

但是,我建议在js内进行改进并进行小型控制器检查.

当我们使用@Urlhelper来调用一个动作时,我们将收到一个格式化的html.最好更新content(.html)而不是实际的element(.replaceWith).

更多关于:jQuery的replaceWith()和html()有什么区别?

$.get( '@Url.Action("details","user", new { id = Model.ID } )', function(data) {
    $('#detailsDiv').html(data);
}); 
Run Code Online (Sandbox Code Playgroud)

这在树中特别有用,其中内容可以多次更改.

在控制器上,我们可以根据请求者重用该操作:

public ActionResult Details( int id )
{
    var model = GetFooModel();
    if (Request.IsAjaxRequest())
    {
        return PartialView( "UserDetails", model );
    }
    return View(model);
}
Run Code Online (Sandbox Code Playgroud)


Pet*_*ter 11

您可以尝试的另一件事(基于tvanfosson的答案)是这样的:

<div class="renderaction fade-in" 
    data-actionurl="@Url.Action("details","user", new { id = Model.ID } )"></div>
Run Code Online (Sandbox Code Playgroud)

然后在页面的脚本部分:

<script type="text/javascript">
    $(function () {
        $(".renderaction").each(function (i, n) {
            var $n = $(n),
                url = $n.attr('data-actionurl'),
                $this = $(this);

            $.get(url, function (data) {
                $this.html(data);
            });
        });
    });

</script>
Run Code Online (Sandbox Code Playgroud)

这将使用ajax呈现您的@ Html.RenderAction.

为了让所有迷人的sjmansy你可以使用这个css添加淡入效果:

/* make keyframes that tell the start state and the end state of our object */
@-webkit-keyframes fadeIn { from { opacity:0; } to { opacity:1; } }
@-moz-keyframes fadeIn { from { opacity:0; } to { opacity:1; } }
@keyframes fadeIn { from { opacity:0; } to { opacity:1; } }

.fade-in {
    opacity: 0; /* make things invisible upon start */
    -webkit-animation: fadeIn ease-in 1; /* call our keyframe named fadeIn, use animattion ease-in and repeat it only 1 time */
    -moz-animation: fadeIn ease-in 1;
    -o-animation: fadeIn ease-in 1;
    animation: fadeIn ease-in 1;
    -webkit-animation-fill-mode: forwards; /* this makes sure that after animation is done we remain at the last keyframe value (opacity: 1)*/
    -o-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
    -webkit-animation-duration: 1s;
    -moz-animation-duration: 1s;
    -o-animation-duration: 1s;
    animation-duration: 1s;
}
Run Code Online (Sandbox Code Playgroud)

男人我喜欢mvc :-)


Chr*_*ann 9

您需要在Controller上创建一个Action,它返回"UserDetails"局部视图或控件的渲染结果.然后只需使用来自jQuery的Http Get或Post来调用Action来显示渲染的html.


Dev*_*evC 5

使用标准的 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);
        }
Run Code Online (Sandbox Code Playgroud)