【发布时间】:2019-05-20 07:29:22
【问题描述】:
我是 ASP.NET MVC Web 应用程序的新手。
我在尝试访问时收到以下错误: http://localhost:1160/View/ViewMovies
ViewMovies 是一个将模型返回给视图的动作。同样,我有一个名为 ViewCustomers 的类似操作,它也给了我同样的错误。
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);
}
}
我添加了一个名为 Movie_Customer 的视图文件夹:
它有两个单独的 .cshtml 文件,分别名为 Customers.cshtml 和 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>
}
}
我正在做的正是这里所做的:http://techfunda.com/howto/240/return-model-to-view-from-action-method
我做错了什么?
如何消除这些错误?
关于处理视图或视图模型,我应该知道什么?
提前致谢。
【问题讨论】:
-
所以错误信息是不言自明的。根据约定,您查看文件应位于这些目录之一,并且视图名称应与操作方法名称匹配。但是如果需要,您可以通过显式传递视图路径来覆盖约定。确保您的视图被强类型化为与您从操作方法返回/传递到视图的数据相同的类型。
-
你的控制器应该命名为
MovieCustomerController,你的视图文件夹应该命名为Views/MovieCustomer。然后您可以在返回值中指定视图名称,例如return View("Customers", model). -
@Shyju 我已经更改了名称并且可以正常工作。谢谢。但我对此感到困惑。如果我的控制器还包含更多操作(显然名称不同),它们使用相同的 .cshtml 视图文件但名称与 .cshtml 文件不同,该怎么办?
-
你可以显式传递一个视图
return View("~/Views/Customer/index.cshtml, listOdCustomers)`
标签: c# asp.net-mvc model-view-controller model server-error