如何将现有视图附加到控制器操作?

时间:2013-01-31 13:10:33

标签: c#-4.0 asp.net-mvc-4

如何将现有视图附加到动作? 我的意思是,我已经将这个视图附加到一个动作,但我想要的是附加到第二个动作。

实施例: 我有一个名为Index的Action和一个View,同名,附加到它,右键单击,添加视图......,但现在,如何附加到第二个?假设一个名为Index2的Action,如何实现呢?

以下是代码:

//this Action has Index View attached
public ActionResult Index(int? EntryId)
{
   Entry entry = Entry.GetNext(EntryId);

   return View(entry);
}

//I want this view Attached to the Index view...
[HttpPost]
public ActionResult Rewind(Entry entry)//...so the model will not be null
{
   //Code here

   return View(entry);
}
我用Google搜索了一下,无法找到合适的答案...... 有可能吗?

2 个答案:

答案 0 :(得分:7)

您无法将操作“附加”到视图,但您可以使用Controller.View方法

定义操作方法要返回的视图
public ActionResult MyView() {
    return View(); //this will return MyView.cshtml
}
public ActionResult TestJsonContent() {
    return View("anotherView");
}

http://msdn.microsoft.com/en-us/library/dd460331%28v=vs.98%29.aspx

答案 1 :(得分:4)

这有帮助吗?您可以使用View的重载来指定不同的视图:

 public class TestController : Controller
{
    //
    // GET: /Test/

    public ActionResult Index()
    {
        ViewBag.Message = "Hello I'm Mr. Index";

        return View();
    }


    //
    // GET: /Test/Index2
    public ActionResult Index2()
    {
        ViewBag.Message = "Hello I'm not Mr. Index, but I get that a lot";

        return View("Index");
    }


}

这是View(Index.cshtml):

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>@ViewBag.Message</p>
相关问题