ASP.NET MVC使用Ajax刷新Partial View


Model:

    public class TestModel
    {
        [Required]
        public string Id { get; set; }
    }

Controller:

    public class TestController : Controller
    {
        // GET: Test
        public ActionResult Index()
        {
            ViewData["Name"] = "NULL";
            return View();
        }

        [HttpPost]
        public ActionResult TestRefresh()
        {
            var list = new List<TestModel>() { new TestModel { Id = "1" }, new TestModel { Id = "2" } };
            return PartialView("PartialInput", list);
        }
    }

View:

@{
    ViewBag.Title = "Index";
}

<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
    $(document).ready(function () {
        $("#btRefresh").click(function () {
            $.ajax({
                type: "POST",
                url: "/Test/TestRefresh",// Controller名(TestController)/Method"
                success: function (data) {
                    $("#TestDiv").html(data);// Partial View中的div
                },
                error: function (msg) {
                    alert('error:' + msg);
                }
            });
        });
    });

</script>

<body>
    @{
        <div>
            @{
                Html.RenderPartial("PartialInput");
            }
        </div>
        <input type="text" id="textRefresh">
        <input type="submit" id="btRefresh" value="Refresh">
    }
</body>

Partial View:

@model List<partialview.Models.TestModel>

<style>
    .green-background {
        background-color: yellow;
    }
</style>

<div id="TestDiv" class="green-background">
    @{
        if (Model == null)
        { return; }
    }
    @foreach (var item in Model)
    {
        <ul>
            <li>@item.Id</li>
        </ul>
    }
</div>

演示:

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM