从操作返回模型以进行查看

时间:2018-12-19 18:46:33

标签: c# asp.net-mvc model-view-controller model server-error

我是ASP.NET MVC Web应用程序的新手。

尝试访问时出现以下错误: http://localhost:1160/View/ViewMovies

ViewMovies是一个将模型返回到View的动作。同样,我有一个名为ViewCustomers的类似动作,它也给我同样的错误。

错误 enter image description here

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的视图文件夹:

enter image description here

它有两个独立的.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

我做错了什么?
如何清除这些错误? 关于处理视图或视图模型,我应该知道些什么?

谢谢。

2 个答案:

答案 0 :(得分:1)

您的控制器名为ViewController,按照约定,框架将检查~Views/<ControllerNamePrefix>/目录和Views/Shared/目录中是否有与您所请求名称匹配的视图文件(此处您正在请求{ {1}}和ViewCustomers,因为您使用的是ViewMovies,因此框架将查找名称与操作匹配的视图。如果要指定视图的名称,请使用{{1} })

要解决错误,可以将视图重命名为return View(model)return View("ViewName", model),然后将这些文件放在新目录中:位置ViewCustomers.cshtml

就个人而言,我也建议您重命名控制器,因为ViewMovies.cshtml并没有真正说明控制器应负责的内容。在MVC应用程序中,大多数所有控制器都将返回视图。

总结:

  • 您正在请求名为/Views/View/ViewController的视图,这些视图在任何文件夹中都不存在。
  • 您的视图不在写入中 ViewCustomers.cshtml文件夹中的子目录,以便框架可以找到 他们。

答案 1 :(得分:1)

我认为您很困惑,因为在尝试从控制器返回视图时,您必须采用文字名称并将其作为

放在返回溢出中
return View("Customer",model) 

或者在构造控制器时,您可能需要右键单击控制器的名称,然后为所选控制器选择“创建视图”选项,这将自动将这两者绑定在一起。

视图与控制器的命名约定不同

相关问题