如何在动作方法中返回其他视图?

时间:2014-01-31 10:08:24

标签: asp.net asp.net-mvc asp.net-mvc-4

我想在create action方法中返回索引操作方法的视图。我尝试在索引操作方法中编写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"); 
    }   
}

2 个答案:

答案 0 :(得分: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 :(得分: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的。