2013-08-05 31 views
0

我想要做的是從控制器內調用警報對話框。 推理是因爲控制器被視圖通過ajax調用調用,並且不會重新加載頁面,因此將無法比較tempdata中的任何新數據或其他。從控制器調用警報框

該行爲的目的是檢查入學的學生是否應該在那裏。如果課程不在他們的時間表中,那麼權限布爾仍然是錯誤的,並且會彈出一個警告,聲明學生不在課堂中。

public ActionResult Action(string ccod, int sid) 
    { 
     IEnumerable<MvcStudentTracker.Databases.Course> result = from course in db.Courses 
        join sched in db.Schedules on course.CourseCode equals sched.ClassCode 
        where sched.StuID == sid 
        select course; 
     bool permission = false; 
     foreach (var item in result) 
     { 
      if (item.CourseCode == ccod) 
       permission = true; 
     } 

     if (permission == false) 
     { 
      //call alert dialog box "This student is not signed up for this class" 
     } 
     return null; 

    } 
+3

爲什麼不能用'permission'狀態,然後在你的Ajax調用成功使用該值返回'JsonResult'顯示警報? –

+0

或者,如果你真的想,只需設置一個ViewBag變量並在聲明你的JS函數來顯示對話框時使用它。 – user1477388

+0

因爲我是mvc的新手,不知道這是一個選項。我會試一試。謝謝。 – RSpraker

回答

2

讓我們更改您的操作,使其返回JsonResult對象。這樣我們可以輕鬆地在客戶端操縱其結果。正如你已經使用javascript調用它,這是最好的解決方案。

所以,你行動

public JsonResult Action(string ccod, int sid) 
{ 
    IEnumerable<MvcStudentTracker.Databases.Course> result = from course in db.Courses 
       join sched in db.Schedules on course.CourseCode equals sched.ClassCode 
       where sched.StuID == sid 
       select course; 

    return Json(result.Any(x => x.CourseCode == ccod), JsonRequestBehavior.AllowGet); 
} 

而且你視圖

$.ajax({ 
    url: 'root/Action', 
    cache: false, 
    type: 'GET', 
    data: { 
     ccod: $('...').val() 
     , sid: $('...').val() 
    }, 
    dataType: 'json' 
}).done(function (data) { 
    if (data) { 
     //ok! 
    } 
    else { 
     //permission denied 
    } 
}); 

請注意,我已經改變了你的行動代碼。您可能想要查看它並將其更改一些。

0

添加到您的代碼:

Page.ClientScript.RegisterStartupScript(Page.GetType(), "alrt", "alert('Anything');", true); 

像htis

public ActionResult Action(string ccod, int sid) 
     { 
      IEnumerable<MvcStudentTracker.Databases.Course> result = from course in db.Courses 
         join sched in db.Schedules on course.CourseCode equals sched.ClassCode 
         where sched.StuID == sid 
         select course; 
      bool permission = false; 
      foreach (var item in result) 
      { 
       if (item.CourseCode == ccod) 
        permission = true; 
      } 

      if (permission == false) 
      { 
       //call alert dialog box "This student is not signed up for this class" 
    Page.ClientScript.RegisterStartupScript(Page.GetType(), "alrt", "alert('This student is not signed up for this class');", true); 
      } 
      return null; 

     }