Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to attach an existing View to a controller action?

How can I attach an existing View to an Action? I mean, I've already attached this very View to an Action, but what I want is to attach to a second Action.

Example: I've an Action named Index and a View, same name, attached to it, right click, add view..., but now, how to attach to a second one? Suppose an Action called Index2, how to achieve this?

Here's the code:

//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);
}

I googled it and cant find an proper answer... It's possible?

like image 730
ramires.cabral Avatar asked Jan 31 '13 13:01

ramires.cabral


2 Answers

you cannot "attach" actions to views but you can define what view you want be returned by an action method by using Controller.View Method

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

like image 107
Massimiliano Peluso Avatar answered Oct 07 '22 04:10

Massimiliano Peluso


Does this help? You can use the overload of View to specify a different 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");
    }


}

Here is the View (Index.cshtml):

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>@ViewBag.Message</p>
like image 39
Mike the Tike Avatar answered Oct 07 '22 04:10

Mike the Tike