【问题标题】:Model type reference not working in mvc view [closed]模型类型引用在 mvc 视图中不起作用 [关闭]
【发布时间】:2016-05-11 04:56:21
【问题描述】:

它正在使用ViewDataViewBag,但尝试强类型模型绑定,无法构建模型类型引用

我想念任何人并且做错了什么。

查看:

@model  Working_with_Views.Models.Product;
@{
  var product  = Model;
}
<h3>Name: @product.Title</h3>
<h2>Price: @product.Price</h2>
<h5>Produce Date: @product.ProduceDate</h5>

查看页面编译时错误

型号:

namespace Working_with_Views.Models
{
    public class Product
    {
        public int ProductId { get; set; }
        public string ImgePath { get; set; }
        public string Title { get; set; }
        public DateTime ProduceDate { get; set; }
        public DateTime  LeftDateExpire { get; set; }
        public decimal Price { get; set; }
    }
}

控制器:

 public ActionResult Index()
    {

        Product product = new Product()
        {
            Title = "Pepsi",
            Price = 30.00m,
            ProduceDate = DateTime.Now,
            LeftDateExpire = DateTime.Now.AddDays(7),
        };

        return View(product);
    }

【问题讨论】:

  • 您需要在模型声明之后删除;(并在您的问题中添加代码和错误消息,而不是它的图像)
  • 我认为这是需要的;语句是否结束
  • 对不起,我不明白你的评论。
  • "你需要在模型声明之后删除 ;" 但是为什么呢?如果使用 ; 为什么不工作在模型声明之后。云你解释我:)
  • 您使用的是 razor,因此您必须遵循 razor 的语法才能使代码正常工作

标签: c# asp.net-mvc asp.net-mvc-4 razor-2


【解决方案1】:

model 传递给视图或通过ViewBagViewData 使用它是做同一件事的两种完全不同的方式。实现方式各不相同。

在您的情况下,您错误地将模型传递给视图 - 事实上,您甚至没有通过它。您只是指定可以找到模型的位置。您需要指定整个namespace,包括型号名称,在您的情况下为Product

@model Working_with_Views.Models.Product

现在您已将模型传递给视图,现在您可以随意使用了。

使用以下不方便,因为如果您不指定,视图如何知道您的模型是Product?如果还有CustomerAddressCountry等其他模型会怎样?你的视图怎么知道它必须使用Product

@model  Working_with_Views.Models;

这就是为什么您需要向视图指定要使用的模型的原因。

你甚至不需要这部分,因为你可以直接使用模型:

@{
     var product  = Model;
}

删除上述代码,您可以使用控制器传入的模型,如下所示:

<h3>Name: @Model.Title</h3>
<h2>Price: @Model.Price</h2>
<h5>Produce Date: @Model.ProduceDate</h5>

我希望这可以为您在视图中使用模型时提供更多的说明。

【讨论】:

  • 我指定的操作,不幸的是没有添加。现在你看到更新我的视图
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-26
  • 1970-01-01
  • 2013-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多