简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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