【问题标题】:Passing CSS Values Through JavaScript to Partial View通过 JavaScript 将 CSS 值传递给局部视图
【发布时间】:2018-01-17 21:38:37
【问题描述】:

我正在使用 MVC 实体框架 Web 应用程序。我有一个视图显示每 30 秒更新一次的其他部分视图。问题是我使用的动态进度条根本没有填满,我已经尝试了我所知道的一切。我认为的问题是传递给部分视图(“宽度”,current_progress +“%”)的css。这是一张照片,酒吧应该是半满的......

控制器方法:

    public ActionResult Dashboard()
    {
        ViewBag.SumofDon = db.tblDonors.Sum(s => s.DonationAmount);
        return View(db.tblDonors.ToList());
    }

    public ActionResult Progress()
    {
        return PartialView("_Progress", db.tblDonors.ToList());
    }

Dashboard.cshtml:

@model IEnumerable<bssp.Models.tblDonor>

@{
    ViewBag.Title = "Dashboard";
}

@section Scripts{

<script>
function loadProgressPV() {
    $.ajax({
    url: "@Url.Action("Progress")",
    type: 'GET', // <-- make a async request by GET
    dataType: 'html', // <-- to expect an html response
    success: function(result) {
                $('#progress').html(result);
             }
   });
}

$(function() {
    loadProgressPV(); // first time
    // re-call the functions each 10 seconds
    window.setInterval("loadProgressPV()", 10000);
});
</script>

<script>
$(function () {
    var SumofDon = @ViewBag.SumofDon;
    var current_progress = (SumofDon / 20000) * 100; // 20000 is the goal that can be changed
    $("#dynamic")
        .css("width", current_progress + "%") //This causes the problem?
});
</script>

}

<div class="container-fluid">
    <div class="row" id="progress">
        @Html.Partial("_Progress")
    </div>
</div>

局部视图:

@model IEnumerable<bssp.Models.tblDonor>

<div class="row">
<br /><br /><br />
<div class="col-md-12">
    <div class="well bs-component">
        <h4>@String.Format("{0:C}", @ViewBag.SumofDon) out of $20,000<br /></h4>
        <div class="progress progress-striped active">
            <div class="progress-bar" id="dynamic" style="width: 0%"></div> @*The width is what gets updated because it found the id of dynamic*@
        </div>
    </div>
</div>
</div>

任何帮助都会很棒,提前感谢!

【问题讨论】:

  • 它应该可以工作。您确定 current_progress 设置正确吗?
  • @Alex 你尝试使用 $(document).ready(function(){ // 你的代码 })
  • 你的部分有 style="width: 0%" 并且你的 ajax 不会重新运行设置宽度的 jQuery。
  • 由于您正在创建部分内容并将 html 从其中放入页面,因此我将直接在剃须刀中进行宽度计算。
  • @nurdyguy 呵呵!那工作得很好。只需将我在脚本中声明的 var 移动到部分视图中的 @{} 中,然后将宽度元素中的 0 替换为 current_progress。谢谢大佬!

标签: javascript css ajax asp.net-mvc asp.net-mvc-4


【解决方案1】:

我认为您的问题是您使用 style="width: 0%" 从部分中提取 html,但是调整 css 的 jQuery $("#dynamic").css("width", current_progress + "%") 仅在页面加载时运行,而不是在部分重新加载后运行。你有两个选择来解决这个问题,

  1. 在 razor 从部分加载后运行 jQuery 函数,在 ajax 的 success 方法中。

  2. 既然您使用 razor 创建局部,为什么不直接在此处进行计算呢?这样,部分就已经设置了宽度集。这是两者中更简单、更快捷的选择。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-19
    相关资源
    最近更新 更多