简体   繁体   English

为什么我不能从MVC访问新产品列表?

[英]why i can not access new product List from MVC?

Hi! 嗨! i try to learn Asp.net MVC.i created a sample application to learn it. 我尝试学习Asp.net MVC.i创建了一个示例应用程序来学习它。 But press f5 return server error. 但是按f5键返回服务器错误。 Where do l make a mistake? 我在哪里犯错? where is the problem? 问题出在哪儿? there is a navigator bar Home/About/Product . 有一个导航栏Home / About / Product。 if i press Product, error return to me. 如果我按产品,则会返回错误。

在此处输入图片说明 Cotroller: 主控台:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models.Db;

namespace MvcApplication1.Controllers
{
    public class ProductsController : Controller
    {
        //
        // GET: /Products/

        public ActionResult GetAll()
        {
            using (var ctx = new MyDbEntities())
            {
                ViewData["Products"] = ctx.Products;
                return View();
            }

        }

    }
}

View: 视图:


<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.Db.Product>" %>
<%@ Import Namespace="MvcApplication1.Models.Db" %>
<%@ Import Namespace="MvcApplication1.Controllers" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    ProductDetail
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>ProductDetail</h2>
    <ul>

<% foreach (var m in (IEnumerable<Products>)ViewData["Products"])
     { %>

     <li><%= m.ProductName %></li>

<% } %>
</ul>

</asp:Content>

site.Master: site.Master:



            <div id="menucontainer">

                <ul id="menu">              
                    <li><%: Html.ActionLink("Home", "Index", "Home")%></li>
                    <li><%: Html.ActionLink("About", "About", "Home")%></li>
                     <li><%: Html.ActionLink("Product", "ProductDetail", "Product")%></li>
                </ul>

            </div>
<%: Html.ActionLink("Product", "ProductDetail", "Product")%>

the action name ProductDetail is not in your controller you have GetAll action name 操作名称ProductDetail不在您的控制器中,您具有GetAll操作名称

u need 你需要

 public ActionResult ProductDetail()
    {
        using (var db = new NorthwindEntities())
        {
            return View(db.Products.ToList());
        }
    }

Can you provide more information such as the actual server error? 您能否提供更多信息,例如实际服务器错误?

Quickly looking at the code the View name is wrong. 快速查看代码,视图名称是错误的。 going to /Products/ expects a view named Products not product details. 转到/ Products /会看到一个名为Products而不是产品详细信息的视图。

There is a mismatch between the Controller name and the View folder name. 控制器名称和视图文件夹名称之间不匹配。 Also between the Action name and the View name. 同样在动作名称和视图名称之间。

Products Controller -> Product Folder in Views 产品控制器->视图中的产品文件夹

GetAll Action -> ProductDetail.aspx View GetAll操作-> ProductDetail.aspx视图

Rename to: 重命名为:

Product Controller -> Product Folder in Views 产品控制器->视图中的产品文件夹

ProductDetail Action -> ProductDetail.aspx View ProductDetail操作-> ProductDetail.aspx视图

Also, make this line: 另外,使这一行:

ViewData["Products"] = ctx.Products;

like this: 像这样:

ViewData["Products"] = ctx.Products.ToList();

Your views shouldn't be making calls to the database. 您的视图不应该调用数据库。

Assuming you doing the default routing. 假设您执行默认路由。

  1. The Problem is that your controller is named ProductsController (pluralized). 问题在于您的控制器名为ProductsController (复数形式)。 Change the name to ProductController or the name of the viewfolder to Products . 将名称更改为ProductController或将视图文件夹的名称更改为Products

  2. Another problem is that your Controller does not contain a ActionMethod ProductDetail , your link in the site.Master pointing to ProductController.ProductDetail 另一个问题是您的Controller不包含ActionMethod ProductDetail ,您在site.Master中的site.Master指向ProductController.ProductDetail

If you want to learn Asp.NET Mvc i encourage you to check out the following tutorials. 如果您想学习Asp.NET Mvc,建议您阅读以下教程。

hope this helps 希望这可以帮助

First of all, try to be more specific. 首先,尝试更加具体。 What error do you get? 你得到什么错误?

Now, I think I see what the problem is, but I'm just guessing because you didn't post the error. 现在,我想我知道问题出在哪里,但是我只是在猜测,因为您没有发布错误。 For what I see, you pass to the view the IQueryable: ctx.Products without enumerating it. 对于我所看到的,您无需枚举即可将其传递给IQueryable: ctx.Products视图。

Then the view tries to enumerate it, but the context is disposed, so the query cannot run. 然后,视图尝试枚举它,但是上下文被丢弃,因此查询无法运行。 I guess the error you're getting is something like "the context is not available" or something like this. 我猜您收到的错误是诸如“上下文不可用”之类的东西。

First of all, try to change the statement like this: ctx.Products.ToList() and see if the error goes away. 首先,尝试更改如下语句: ctx.Products.ToList()然后查看错误是否消失。

Another thing I spotted you're using the dictionary, while using a strongly typed ViewModel would be much better (or at least use dynamic). 我发现您正在使用字典的另一件事,而使用强类型的ViewModel会更好(或至少使用动态)。

if you do not specify a View name, the application will look for a view with the name of your method. 如果未指定View名称,则应用程序将查找带有您的方法名称的视图。 Ie: 即:

public ActionResult GetAll()
    {
        using (var ctx = new MyDbEntities())
        {
            ViewData["Products"] = ctx.Products;
            return View();
        }

    }

Is looking for a view "Product/GetAll.aspx". 正在寻找一个视图“ Product / GetAll.aspx”。 Solutions: 解决方案:

  • change the name of the method 更改方法名称
  • change the name of the view 更改视图名称
  • Specify the view name by doing return View("ProductDetail"); 通过执行return View("ProductDetail");指定视图名称return View("ProductDetail");

为什么我不能从列表中投射<myclass>列出<object> ?<div id="text_translate"><p> 我有一个对象列表,它们属于我的QuoteHeader类型,我想将此列表作为对象列表传递给能够接受List&lt;object&gt;的方法。</p><p> 我的代码行显示...</p><pre> Tools.MyMethod((List&lt;object&gt;)MyListOfQuoteHeaders);</pre><p> 但是我在设计时收到以下错误...</p><pre> Cannot convert type 'System.Collections.Generic.List&lt;MyNameSpace.QuoteHeader&gt;' to 'System.Collections.Generic.List&lt;object&gt;'</pre><p> 我需要对我的 class 做任何事情来允许这样做吗? 我认为所有类都继承自 object 所以我不明白为什么这不起作用?</p></div></object></myclass> - Why can't I cast from a List<MyClass> to List<object>?

如何访问列表<object>来自 appsettings.Json?<div id="text_translate"><p> 在我的 appsettings.json 我有一个这样的字段</p><pre> "MyFields": [ { "name":"one", "type":"type1" "parameters":[{"key":"url","value":"myurl.com"}, {"key":"data","value":"mydata"}] }, { "name":"two", "type":"type2"... .. and so on } ]</pre><p> 我制作了一个具有以下属性的 class Myfield:</p><pre> public class MyField { [JsonProperty] public string? name { get; set; } [JsonProperty] public string? type { get; set; } [JsonProperty] public IDictionary<string,string>? parameters { get; set; } }</pre><p> 我正在尝试使用配置在另一个 class 中访问它,如下所示:</p><pre> //config is the configuration var myFields = config.GetSection("MyFields").Get<List<MyField>>();</pre><p> 问题是 myFields 结果是空的。 但是当我通过消除“参数”字段来做同样的事情时,它就像一个魅力。</p><p> 我知道这与匹配不当有关,但能得到一些帮助会很棒。</p></div></object> - How can I access a List<object> from appsettings.Json?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我不能访问List的类内部 <T> 当我从中得出? - Why can't I access the class internals of List<T> when I derive from it? 为什么我不能在按钮事件中添加新的List对象 - why can't I add a new List object in button event 如何从现有列表创建新列表? - How can I create new list from existing list? 如何在MVC4中将视图中的列表返回到控制器 - How can I return a list from view to controller in MVC4 为什么我不能从列表中投射<myclass>列出<object> ?<div id="text_translate"><p> 我有一个对象列表,它们属于我的QuoteHeader类型,我想将此列表作为对象列表传递给能够接受List&lt;object&gt;的方法。</p><p> 我的代码行显示...</p><pre> Tools.MyMethod((List&lt;object&gt;)MyListOfQuoteHeaders);</pre><p> 但是我在设计时收到以下错误...</p><pre> Cannot convert type 'System.Collections.Generic.List&lt;MyNameSpace.QuoteHeader&gt;' to 'System.Collections.Generic.List&lt;object&gt;'</pre><p> 我需要对我的 class 做任何事情来允许这样做吗? 我认为所有类都继承自 object 所以我不明白为什么这不起作用?</p></div></object></myclass> - Why can't I cast from a List<MyClass> to List<object>? 如何自动在列表中生成新的Guid <Expense> 从视图模型,并使用Asp.Net MVC将值传递到Controller的foreach循环? - How can I automatically generate new Guid inside of list<Expense> from viewmodel and pass value to foreach loop of Controller using an Asp.Net MVC? 如何从Sage Line 50访问产品列表? - How to access the product list from Sage Line 50? 如何访问列表<object>来自 appsettings.Json?<div id="text_translate"><p> 在我的 appsettings.json 我有一个这样的字段</p><pre> "MyFields": [ { "name":"one", "type":"type1" "parameters":[{"key":"url","value":"myurl.com"}, {"key":"data","value":"mydata"}] }, { "name":"two", "type":"type2"... .. and so on } ]</pre><p> 我制作了一个具有以下属性的 class Myfield:</p><pre> public class MyField { [JsonProperty] public string? name { get; set; } [JsonProperty] public string? type { get; set; } [JsonProperty] public IDictionary<string,string>? parameters { get; set; } }</pre><p> 我正在尝试使用配置在另一个 class 中访问它,如下所示:</p><pre> //config is the configuration var myFields = config.GetSection("MyFields").Get<List<MyField>>();</pre><p> 问题是 myFields 结果是空的。 但是当我通过消除“参数”字段来做同样的事情时,它就像一个魅力。</p><p> 我知道这与匹配不当有关,但能得到一些帮助会很棒。</p></div></object> - How can I access a List<object> from appsettings.Json? 为什么新线程可以访问UI? - Why can new threads access the UI? 如何访问列表 <KeyValuePair<string,int> &gt;来自MongoDB - How can I access List<KeyValuePair<string,int>> from MongoDB
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM