2013-05-04 149 views
1

這是我的代碼,我想在這裏發佈一些數據(這裏是日曆日期)到「home」控制器的「索引」動作,並且想要將這些數據保存到數據庫中,同時我想重定向到「家」的控制器從一個動作重定向到另一個控制器動作在mvc

這裏的另一個控制器,即「指數」行動的另一個動作是我下面的jQuery代碼,

function getDate() { 

      $('.cal_daybox').on('click', function() { 

      var timestamp = parseInt($(this).attr('id')); 

       var day = new Date(timestamp); 

       alert("You clicked " + day.toDateString()); 

       var url = '@Url.Content("~/Home/Index")'; 
       var date = day.toDateString(); 
       $.ajax({ 
        type: "POST", 
        url: url, 
        data: { date: day.toDateString() }, 
        dataType:"json" 
       });     
      return false; 
      }); 

EventsController.cs

public ActionResult Index() 
    { 
     return View(db.Events.ToList()); 
    } 

個HomeController.cs

[HttpPost] 
    public ActionResult Index(DateTime date) 
    { 

      Date dt = new Date(); 
      dt.StartDate = date; 
      db.Dates.Add(dt); 
      db.SaveChanges(); 
      return RedirectToAction("Index", "Events", new { id = dt.DateID }); 
    } 
+0

是它不工作 – 2013-05-04 07:44:40

+0

索引操作::公衆的ActionResult指數(){ 回報 景( db.Events.ToList()); } – 2013-05-04 07:50:24

+0

問題是我無法同時發佈數據並重定向到另一個頁面,因爲在調試器中它顯示我重定向,但實際上它沒有被重定向。 – 2013-05-04 08:00:47

回答

0

你活動的指標動作控制器沒有一個參數,以收到的Dateid value.It無法找到,可以免費獲贈DateId VAL一個動作。

你需要或者修改現有的動作或添加了操作過載像這種事件

public ActionResult Index(DateTime dateId) 
{ 
    //Do something with the val 
} 

public ActionResult Index() 
{ 
    return View(db.Events.ToList()); 
} 
0
you are calling controller action using ajax so in this case you have to change you action method and jquery call like this: 




     [HttpPost] 
     public ActionResult Index(DateTime date) 
     { 

      Date dt = new Date(); 
      dt.StartDate = date; 
      db.Dates.Add(dt); 
      db.SaveChanges(); 
      return Json(dt.DateID,JsonAllowBehaviour.AllowGet); 
      // return RedirectToAction("Index", "Events", new { id = dt.DateID }); 
     } 
    function getDate() { 

      $('.cal_daybox').on('click', function() { 

      var timestamp = parseInt($(this).attr('id')); 

       var day = new Date(timestamp); 

       alert("You clicked " + day.toDateString()); 

       var url = '@Url.Content("~/Home/Index")'; 
       var date = day.toDateString(); 
       $.ajax({ 
        type: "POST", 
        url: url, 
        data: { date: day.toDateString() }, 
        dataType:"json", 
        onsuccess:function(id) 
           { 
window.location='/Events/Index?Id='+id; 
            } 
       });     
      return false; 
      }); 


And also please change your index action of Events Controller like below: 
public ActionResult Index(int Id=0) 
{ 
    return View(db.Events.ToList()); 
} 
相關問題