更新PartialView mvc 4

Mar*_*ero 22 c# partial-views viewbag asp.net-mvc-4

安永!如何使用模型中的数据刷新部分视图?第一次,当页面加载它正常工作时,但不是当我从Action调用它时.我创建的结构如下:

在我看来的任何地方:

 @{ Html.RenderAction("UpdatePoints");}
Run Code Online (Sandbox Code Playgroud)

我的PartialView"UpdatePoints":

<h3>Your points are @ViewBag.points </h3>
Run Code Online (Sandbox Code Playgroud)

在控制器我有:

public ActionResult UpdatePoints()
        {

            ViewBag.points =  _Repository.Points;
            return PartialView("UpdatePoints");
        }
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

UPDATE

感谢你的帮助!最后我按照你的建议使用JQuery/AJAX,使用模型传递参数.

所以,在JS中:

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

在控制器中:

var model = _newPoints;
return PartialView(model);
Run Code Online (Sandbox Code Playgroud)

在视图中

<div id="divPoints"></div>
@Html.Hidden("newpoints", Model)
Run Code Online (Sandbox Code Playgroud)

And*_*bal 25

所以,假设您有View with PartialView,必须通过按钮点击更新:

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

<input class="button" value="update" />
Run Code Online (Sandbox Code Playgroud)

有一些方法可以做到这一点.例如,您可以使用jQuery:

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

PostActionToUpdatePoints是您的Actionwith [HttpPost]属性,用于更新点

如果您在动作UpdatePoints()中使用逻辑来更新点,可能您忘记添加[HttpPost]属性:

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

  • 伙计们,这个解决方案有效 虽然很少修理.如果你输入HttpPost注释,你将无法执行Get through jquery加载功能.删除注释."加载"功能是小写的.而post方法是"$ .post"而不是$ $ post.修复这些小东西,它会像魅力一样工作 (4认同)

Ras*_*ara 7

你也可以试试这个.

 $(document).ready(function () {
            var url = "@(Html.Raw(Url.Action("ActionName", "ControllerName")))";
            $("#PartialViewDivId").load(url);
        setInterval(function () {
            var url = "@(Html.Raw(Url.Action("ActionName", "ControllerName")))";
            $("#PartialViewDivId").load(url);
        }, 30000); //Refreshes every 30 seconds

        $.ajaxSetup({ cache: false });  //Turn off caching
    });
Run Code Online (Sandbox Code Playgroud)

它进行初始调用以加载div,然后后续调用以30秒为间隔.

在控制器部分中,您可以更新对象并将对象传递给局部视图.

public class ControllerName: Controller
{
    public ActionResult ActionName()
    {
        .
        .   // code for update object
        .
        return PartialView("PartialViewName", updatedObject);
    }
}
Run Code Online (Sandbox Code Playgroud)