2014-11-03 38 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> 
    } 
}