Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling another different view from the controller using ASP.NET MVC 4

I have a view (Index.cshtml) with a submit button. When the submit button is clicked, it calls an action (Action01) within the controller (TestController.cs) so at the end of the action I want to return to the caller (Index.cshtml) view with a custom view model as a parameter. How do I do this?

Results after first attempt using View("ViewName",model):

An error is raised, as the action is within the controller Test, so returning, it is searching for \Views\Tests\Index, and my Index page is in \Views\Home\Index.

The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:

~/Views/Test/Index.aspx ~/Views/Test/Index.ascx ~/Views/Shared/Index.aspx ~/Views/Shared/Index.ascx ~/Views/Test/Index.cshtml ~/Views/Test/Index.vbhtml ~/Views/Shared/Index.cshtml ~/Views/Shared/Index.vbhtml 

Final solution:

I have used return View("ViewName", model), and I have changed my directories structure as it was the problem.

like image 326
Ralph Avatar asked Sep 20 '13 06:09

Ralph


People also ask

How can we call a view from another controller in MVC?

The shared directory is there specifically to share Views across multiple controllers. Just add your View to the Shared subdirectory and you're good to go. If you do return View("~/Views/Wherever/SomeDir/MyView. aspx") You can return any View you'd like.

How do I navigate to another view in MVC?

You can use the RedirectToAction() method, then the action you redirect to can return a View. The easiest way to do this is: return RedirectToAction("Index", model); Then in your Index method, return the view you want.

Can two different controllers access a single view in MVC?

Yes. Mention the view full path in the View method. If the name of your Views are same in both the controllers, You can keep the Common view under the Views/Shared directory and simply call the View method without any parameter. The View name should be same as the Action method name.


2 Answers

You can directly return a different view like:

return View("NameOfView", Model); 

Or you can make a partial view and can return like:

return PartialView("PartialViewName", Model); 
like image 51
Neel Avatar answered Oct 13 '22 06:10

Neel


To return a different view, you can specify the name of the view you want to return and model as follows:

return View("ViewName", yourModel); 

if the view is in different folder under Views folder then use below absolute path:

return View("~/Views/FolderName/ViewName.aspx"); 
like image 40
Jatin patil Avatar answered Oct 13 '22 07:10

Jatin patil