Search code examples
c#asp.net-mvc-4partial-viewsviewbag

Updating PartialView mvc 4


Ey! How I could refresh a Partial View with data out of the Model? First time, when the page loads it's working properly, but not when I call it from the Action. The structure I've created looks like:

Anywhere in my View:

 @{ Html.RenderAction("UpdatePoints");}

My PartialView "UpdatePoints":

<h3>Your points are @ViewBag.points </h3>

At the Controller I have:

public ActionResult UpdatePoints()
        {

            ViewBag.points =  _Repository.Points;
            return PartialView("UpdatePoints");
        }

Thanks for your help!

UPDATE

Thanks all for your help! Finally I used JQuery/AJAX as you suggested, passing the parameter using model.

So, in JS:

$('#divPoints').load('/Schedule/UpdatePoints', UpdatePointsAction);
var points= $('#newpoints').val();
$element.find('PointsDiv').html("You have" + points+ " points");

In Controller:

var model = _newPoints;
return PartialView(model);

In View

<div id="divPoints"></div>
@Html.Hidden("newpoints", Model)

Solution

  • So, say you have your View with PartialView, which have to be updated by button click:

    <div class="target">
        @{ Html.RenderAction("UpdatePoints");}
    </div>
    
    <input class="button" value="update" />
    

    There are some ways to do it. For example you may use jQuery:

    <script type="text/javascript">
        $(function(){    
            $('.button').on("click", function(){        
                $.post('@Url.Action("PostActionToUpdatePoints", "Home")').always(function(){
                    $('.target').load('/Home/UpdatePoints');        
                })        
            });
        });        
    </script>
    

    PostActionToUpdatePoints is your Action with [HttpPost] attribute, which you use to update points

    If you use logic in your action UpdatePoints() to update points, maybe you forgot to add [HttpPost] attribute to it:

    [HttpPost]
    public ActionResult UpdatePoints()
    {    
        ViewBag.points =  _Repository.Points;
        return PartialView("UpdatePoints");
    }