2014-01-31 33 views
0

我想在創建操作方法中返回Index操作方法的視圖。我嘗試在Index操作方法中編寫return View("Index");,但沒有發生任何事情。我的操作方法都在同一個控制器中。我怎樣才能做到這一點?如何在操作方法中返回其他視圖?

代碼:

public class GuestbookController : Controller 
{   
    // GET: /Guestbook/ 
    public ActionResult Index() 
    { 
     SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["GuestbookContext"].ToString()); 
     string query = string.Format("Select * from Guestbook"); 
     SqlCommand cmd = new SqlCommand(query, conn); 
     conn.Open(); 
     SqlDataReader reader = cmd.ExecuteReader(); 
     List<GuestbookEntry> li = new List<GuestbookEntry>(); 
     while (reader.Read()) 
     { 
      GuestbookEntry GuestbookEntry = new GuestbookEntry(); 
      GuestbookEntry.Name = Convert.ToString(reader["Name"]); 
      GuestbookEntry.Message = Convert.ToString(reader["Message"]); 
      GuestbookEntry.Id = Convert.ToInt32(reader["Id"]); 
      GuestbookEntry.DateAdded = Convert.ToDateTime(reader["DateAdded"]); 
      li.Add(GuestbookEntry);  
     } 
     conn.Close(); 
     var mostRecentEntries =(from entry in li orderby entry.DateAdded descending select entry); 
     ViewBag.Entries = mostRecentEntries.ToList(); 
     return View(); 
    } 

    [HttpPost] 
    public ActionResult Create(GuestbookEntry entry) 
    { 
     SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["GuestbookContext"].ToString()); 
     string query = string.Format("Insert into [Guestbook] values ('{0}','{1}','{2}')", entry.Name, entry.Message, DateTime.Now); 
     SqlCommand cmd = new SqlCommand(query, conn); 
     conn.Open(); 
     cmd.ExecuteNonQuery(); 
     conn.Close(); 

     return View("Index"); 
    } 
} 
+0

你是什麼意思'什麼都沒有發生'?我認爲你需要'返回RedirectToAction(「索引」)' – Zabavsky

回答

2

您只使用視圖,而不是動作,所以ViewBag您要填寫,不會是可用的。

您可以使用使用RedirectToAction()將當前操作重定向到其他操作。

[HttpPost] 
public ActionResult Create(GuestbookEntry entry) 
{ 
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["GuestbookContext"].ToString()); 
    string query = string.Format("Insert into [Guestbook] values ('{0}','{1}','{2}')", entry.Name, entry.Message, DateTime.Now); 
    SqlCommand cmd = new SqlCommand(query, conn); 
    conn.Open(); 
    cmd.ExecuteNonQuery(); 
    conn.Close(); 

    return RedirectToAction("Index"); 
} 
+1

感謝人...這真的有幫助....... – Ajay

1

如果你想,如果它是從客戶端調用那麼你應該使用返回索引頁:

return Index(); //If you don't care about adjusting URL on client's machine 

或者

RedirectToAction("Index") //If you want to update client's URL 

請注意,第二選項確實需要完整的往返客戶端並返回到服務器,並且在Ajax調用時不能輕鬆使用,而第一個選項「停留在服務器上」並且可以與Ajax一起使用。

相關問題