简体   繁体   English

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

[英]Render Partial View Using jQuery in ASP.NET MVC

How do I render the partial view using jquery? 如何使用jquery渲染局部视图?

We can render the partial View like this: 我们可以像这样渲染局部视图:

<% Html.RenderPartial("UserDetails"); %>

How can we do the same using jquery? 我们如何使用jquery做同样的事情?

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>

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

$('#user_content').load('@Url.Action("UserDetails","User")');

@tvanfosson rocks with his answer. @tvanfosson摇滚着他的回答。

However, I would suggest an improvement within js and a small controller check. 但是,我建议在js内进行改进并进行小型控制器检查。

When we use @Url helper to call an action, we are going to receive a formatted html. 当我们使用@Url helper来调用一个动作时,我们将收到一个格式化的html。 It would be better to update the content ( .html ) not the actual element ( .replaceWith ). 更新内容( .html )而不是实际元素( .replaceWith )会更好。

More about at: What's the difference between jQuery's replaceWith() and html()? 更多关于: jQuery的replaceWith()和html()有什么区别?

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

This is specially useful in trees, where the content can be changed several times. 这在树中特别有用,其中内容可以多次更改。

At the controller we can reuse the action depending on requester: 在控制器上,我们可以根据请求者重用该操作:

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

Another thing you can try (based on tvanfosson's answer) is this: 您可以尝试的另一件事(基于tvanfosson的答案)是这样的:

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

And then in the scripts section of your page: 然后在页面的脚本部分:

<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>

This renders your @Html.RenderAction using ajax. 这将使用ajax呈现您的@ Html.RenderAction。

And to make it all fansy sjmansy you can add a fade-in effect using this css: 为了让所有迷人的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;
}

Man I love mvc :-) 男人我喜欢mvc :-)

You'll need to create an Action on your Controller that returns the rendered result of the "UserDetails" partial view or control. 您需要在Controller上创建一个Action,它返回“UserDetails”局部视图或控件的渲染结果。 Then just use an Http Get or Post from jQuery to call the Action to get the rendered html to be displayed. 然后只需使用来自jQuery的Http Get或Post来调用Action来显示渲染的html。

Using standard Ajax call to achieve same result 使用标准的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);
        }

I did it like this. 我是这样做的。

$(document).ready(function(){
    $("#yourid").click(function(){
        $(this).load('@Url.Action("Details")');
    });
});

Details Method: 细节方法:

public IActionResult Details()
        {

            return PartialView("Your Partial View");
        }

If you need to reference a dynamically generated value you can also append query string paramters after the @URL.Action like so: 如果需要引用动态生成的值,还可以在@ URL.Action之后追加查询字符串参数,如下所示:

    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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM