动态加载部分视图 [英] Dynamically load Partial Views

查看:25
本文介绍了动态加载部分视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何动态加载局部视图?

我的意思是我有这个视图,比如说 ListProducts,在那里我选择了一些包含产品等的下拉列表,并使用我想要填充部分视图的选定值,这将在一个div 是不可见的,但在 onchange() 事件之后将变得可见,并且包含来自特定选定项目的数据.

解决方案

使用 jQuery 的 $.load() 和控制器返回部分视图的操作.
例如:

HTML

<div id="你的div">

控制器

public virtual ActionResult Index(string id){var myModel = GetSomeData();返回部分(我的模型);}

查看

@model IEnumerable@if (Model == null || Model.Count() == 0){<p>未找到结果</p>}别的{<ul>@foreach(模型中的YourObjects myobject){<li>@myObject.Name</li>}}

How can i dynamically load a Partial View?

I mean I have this view, lets say ListProducts, there I select some dropdownlists with products, etc, and with the selected values from those I wanna fill a partial view, which would be in a div that was invisible but after onchange() event would become visible and with the data from the specific selected items.

解决方案

Use jQuery's $.load() with a controller action that returns a partial view.
For example:

HTML

<script type="text/javascript">
$(document).ready(function()
{
    $("#yourselect").onchange(function()
    {
        // Home is your controller, Index is your action name
        $("#yourdiv").load("@Url.Action("Index","Home")", { 'id' : '123' }, 
                                        function (response, status, xhr)
        {
            if (status == "error")
            {
                alert("An error occurred while loading the results.");
            }
        });
    });
});
</script>

<div id="yourdiv">
</div>

Controller

public virtual ActionResult Index(string id)
{
    var myModel = GetSomeData();
    return Partial(myModel);
}

View

@model IEnumerable<YourObjects>

@if (Model == null || Model.Count() == 0)
{
    <p>No results found</p>
}
else
{
    <ul>
    @foreach (YourObjects myobject in Model)
    {
        <li>@myObject.Name</li>
    }
    </ul>
}

这篇关于动态加载部分视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆