吐司通知没有出现在MVC 4中

约翰

嗨,我是MVC的新手,我一直在尝试建立一个我一直遵循的教程,试图在我在mvc应用程序中成功编辑某些内容时使Toastr消息出现。我认为我已正确完成所有操作,但通知没有弹出。

    bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css",
            "~/Content/toastr.css"));

    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-{version}.js",
        "~/Scripts/toastr.js"));

我将烤面包机添加到了脚本和CSS中,并且两个捆绑包都在布局视图中呈现。在我的编辑操作中,如果成功,我将重定向到Index操作并添加一条消息。

         [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(Restaurant restaurant)
    {
        if (ModelState.IsValid)
        {
            db.Entry(restaurant).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index", new { message = "Added" });
        }
        return View(restaurant);
    }


    public ActionResult Index(string message )
    {

        if (!string.IsNullOrEmpty(message))
        {
            ViewBag.message = message;
        }

        return View(db.Restaurants.ToList());
    }

然后在索引操作中,我正在检查它是否不为空,如果不是,则将消息传递到视图包中。然后在索引视图中,我正在检查视图包是否为空

        @model IEnumerable<OdeToFoodNov1.Models.Restaurant>

     @{
    ViewBag.Title = "Index";
     }

    <h2>Index</h2>

   <p>
    @Html.ActionLink("Create New", "Create")
   </p>
   <table>
     <tr>
     <th>
        @Html.DisplayNameFor(model => model.Name)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.City)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Country)
    </th>
    <th></th>
</tr>

 @foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Name)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.City)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Country)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
        @Html.ActionLink("Reviews", "Index", "Reviews", new { id=item.Id }, null) |
        @Html.ActionLink("Delete", "Delete", new { id=item.Id })
    </td>
</tr>
  }

</table>


  @if (ViewBag.message != null)
    {

<script type="text/javascript">
    $(document).ready(function () {
        toastr.success('Added')
    })
</script>
   }

但是,当我返回索引视图时,没有收到通知吗?任何帮助表示赞赏,如果我缺少明显的东西,对不起。

Mituw16

大多数MVC布局文件都包含一个称为脚本的可选部分(除非作者出于某种原因将其删除)。

在布局文件中查找看起来像这样的一行

@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)

在这种情况下,您要直接插入视图中的任何Javascript都将在加载jQuery加载到最终HTML中

尝试做这样的事情,以便可以确保将注入的JS加载到可选脚本部分中

@section scripts {
    @if (ViewBag.message != null)
    {
    <script type="text/javascript">
        $(document).ready(function () {
            toastr.success('Added')
        });
    </script>
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章