2014-11-03 37 views
0

嗨,我是MVC的新手,我一直在尝试构建一个教程,我一直试图获得一个toastr消息,当我成功编辑我的mvc应用中的某些东西时出现。我想我已经正确地完成了一切,但通知不会弹出。toastr notifcation not appear mvc 4

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()); 
    } 

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

 @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> 
    } 

然而,当我回去的索引视图我没有得到任何通知的出现?任何帮助表示赞赏,对不起,如果我失去了明显的东西。

+0

我敢打赌这个问题是你的脚本的位置...请检查您的浏览器控制台并寻找任何错误..我怀疑你会发现有关$未定义在那里的东西。 MVC默认将脚本放在HTML文件的底部,在这里,我怀疑你正在试图在jQuery被包含在页面之前调用jQuery – mituw16 2014-11-03 15:19:24

+0

我认为就是这样,你知道我应该把代码放在哪里,以便它加载后我的jQuery包?谢谢你的帮助。 – John 2014-11-03 15:28:48

+0

看到我的答案为解决方案:) – mituw16 2014-11-03 15:41:16

回答

1

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

查找一条线,看起来像这样在布局文件

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

在这种情况下,你要直接注入到你的意见的任何JavaScript将被加载到最终的HTML jQuery是加载。

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

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