在mvc中从一个动作重定向到另一个控制器动作

时间:2013-05-04 07:30:32

标签: asp.net-mvc

这是我的代码,我想将一些数据(这里的日历日期)发布到“home”控制器的“索引”操作,并希望将这些数据保存在数据库中,同时我想重定向到另一个另一个控制器的动作,即“Home”控制器的“Index”动作

这是我下面的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 });
    }

2 个答案:

答案 0 :(得分:0)

事件控制器的索引操作没有用于接收Dateid值的参数。它无法找到可以接收DateId值的操作。

您需要修改现有的Action或像这样添加Action Overload

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

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

答案 1 :(得分: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());
}