2013-08-05 30 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; 

     }