I am new to ASP.NET MVC Web Applications.
I am getting the following Error when I try to access: http://localhost:1160/View/ViewMovies
ViewMovies is an Action that returns a Model to View. Likewise, I have a similar Action named ViewCustomers, which is also giving me the same error.
ViewController.cs
public class ViewController : Controller
{
// GET: View
public ActionResult Index()
{
return View();
}
private MovieCustomerViewModel model = new MovieCustomerViewModel();
public ActionResult ViewMovies()
{
model.movies = new List<Movie> {
new Movie{id=1,name="Shrek"},
new Movie{id=1,name="Wall-e"}
};
return View(model);
}
public ActionResult ViewCustomers()
{
model.customers = new List<Customer> {
new Customer{id=1,name="Junaid"},
new Customer{id=1,name="Zohaib"}
};
return View(model);
}
}
I have added a view folder named Movie_Customer:
It has two separate .cshtml files named, Customers.cshtml and Movies.cshtml
Customers.cshtml
@model Ex1.ViewModels.MovieCustomerViewModel
@{
ViewBag.Title = "Customers";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Customers</h2>
<table class="table table-bordered table-hover" />
<tr>
<th>ID</th>
<th>Name</th>
</tr>
@{
foreach (var v in Model.customers)
{
<tr>
<td>v.id</td>
<td>v.name</td>
</tr>
}
}
Movies.cshtml
@model Ex1.ViewModels.MovieCustomerViewModel
@{
ViewBag.Title = "Movies";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Movies</h2>
<table class="table table-bordered table-hover" />
<tr>
<th>ID</th>
<th>Name</th>
</tr>
@{
foreach (var v in Model.movies)
{
<tr>
<td>v.id</td>
<td>v.name</td>
</tr>
}
}
I am doing exactly what's done here: http://techfunda.com/howto/240/return-model-to-view-from-action-method
What am I doing wrong?
How do I remove these errors?
What should I must know about handling Views or View Models?
Thanks in advance.
Your controller is named ViewController
and by convention the framework will check the ~Views/<ControllerNamePrefix>/
directory and Views/Shared/
directory for a view file matching the name that youre requesting (here you're requesting ViewCustomers
and ViewMovies
since you are using return View(model)
the framework will look for a view with a name that matches the action. If you want to specify the name of the view then use return View("ViewName", model)
)
To resolve your error, you can rename your view to ViewCustomers.cshtml
and ViewMovies.cshtml
and put those files in a new directory: location /Views/View/
.
Personally, I'd recommend renaming your controller as well since ViewController
doesn't really say anything about what the controller should be responsible for. In MVC applications, most all controllers will be returning views.
In summary:
ViewCustomers.cshtml
and ViewMovies.cshtml
which don't exist in any folder. Views
folder for the framework to be able to find
them.