简体   繁体   English

从控制器更新局部视图

[英]Updating partial view from controller

I have read some tutorials on how to update a partial view but they all assume a user interaction as a starting point (like a dropdown change that will cause the updating of a some data in a partial view). 我已经阅读了一些有关如何更新局部视图的教程,但它们都以用户交互为起点(例如下拉更改将导致在局部视图中更新某些数据)。 My situation is different: I am trying to update the partial view starting from the controller, without user interaction on the UI. 我的情况有所不同:我试图从控制器开始更新部分视图,而无需用户在UI上进行交互。 If I use such code: 如果我使用这样的代码:

    [HttpPost]
    public ActionResult PerformAction(MyModel mymodel)
    {
        //....do things

        return PartialView("Notification", mymodel);
    }

The browser will display ONLY the partial view. 浏览器将仅显示部分视图。 Suggestions ? 建议? Thanks 谢谢

Here is the main view: 这是主要视图:

@using System.Web.UI.WebControls
@model MyApplication.Models.Mymodel

@{
    ViewBag.Title = "Home Page";
}

<form class="float_left" method="post" action="@Url.Action("Start", "Home")">
    <fieldset>
        @Html.TextBoxFor(m => m.Username, new { Value = Model.Message })
        <input type="submit" value="Subscribe"/>
        <div id="notificationMessage">
            @{ Html.RenderPartial("~/Views/Home/PartialView.cshtml", new PartialViewModel()); }
        </div>
    </fieldset>
</form>

and here the partial: 这里是局部的:

@using System.Web.UI.WebControls
@model HostedExchangeListener.Models.PartialViewModel
@Html.TextBoxFor(m => m.Message, new { Value = Model.Message })

What you need to do is something along these lines: 您需要做的是遵循这些方针:

View 视图

<div id="partialViewContent"> </div>

<script>
$(function () // Once the DOM is loaded
{
    setInterval(function(){ 
        $.get('@Url.Action("Action","Controller")', function(data) {
        $('#partialViewContent').html(data); // Replace whats in the div with the PartialView
    }, 5000); // Every 5 seconds
});

</script>

Controller 控制者

public ActionResult Action()
{
    var mymodel = new MyViewModel();
    //....do things
    return PartialView("Notification", mymodel);
}

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

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