将数据从一个视图传递到另一个视图-MVC

Pass data from one view to another view -MVC

将数据从一个视图传输到另一个视图的最佳方法是什么?或者这是不好的做法?

原因是想把@model.count()从一个view显示到首页,基本上是首页所有view的汇总。有 tempdata、html.helper 等,但我想知道最好和最可靠的方法。从而避免进一步的问题

这是有问题的代码

product.cshtml

<p>Total amount of Products = @Model.Count()</p>

我基本上希望主页上显示相同的值

您必须刷新主页才能使该值变为实际 'update.' 届时您也可以将该值作为参数传回,但我认为这不是您所希望的.

这可能不是最干净的解决方案,但我认为您希望主页上的文本可以通过某些 javascript/jquery.

进行设置

主页有这个片段:

<form id="PassBackVals"
<input type="hidden" name="ProductCount" value="0">
</form> 

<script>$( ".ProductCount" ).change(function() {
  $("$CurrentProductCount").text = $(".ProductCount").val;
});
</script>

并且在主屏幕上显示文本本身的区域将具有类似于

的内容
<p> I'm currently showing <div id="CurrentProductCount">0</div> Products </p>

然后在你的product.cshtml中,你会

<script>$(".ProductCount").val = @Model.Count()
$( ".ProductCount" ).change();
</script>

好的,我研究了其他方法并通过将 viewbag 后面的代码移动到下面的 public 方法中解决了这个问题

    [OutputCache(NoStore = true, Location = OutputCacheLocation.Client, Duration = 10)]
    public ActionResult UpdateTotals()
    {
        JobController j = new JobController();
        ViewBag.JobCount = j.JobCount();

        ProductController p = new ProductController();
        ViewBag.ProductCount = p.ProductCount();

        return PartialView("UpdateTotals");
    }

然后我将 viewbags 添加到局部视图中并使用 setinterval() javascript,

    <div id ="UpdateTotals">
        @{ Html.RenderAction("UpdateTotals");}
</div>

<script>
    setInterval("$('#UpdateTotals').load('/home/UpdateTotals')", 10000);
</script>

我能够根据自己的需要不断刷新数据,而无需通过 javascript.

通过视图拉取数据。

希望这对以后的任何人都有帮助:)