使用@ Html.DisplayNameFor()时在.NET中出错CS0411

时间:2017-04-28 09:02:09

标签: c# asp.net-mvc visual-studio razor

我是.NET的初学者,我正在学习MVC模式。我正在构建一个演示应用程序,演示任何产品的CRUD操作。在使用任何数据库连接之前,我决定使用内存变量进行测试。我的代码如下:

模型类

public class Product
{
    [Key]
    public int Id { get; set; }

    [Required]
    [Display(Name="Name")]
    public String ProductName { get; set; }

    [Required]
    [Display(Name="Price")]
    public float Price { get; set; }

    [Display(Name="Discription")]
    public String ProductDiscription { get; set; }
}

控制器类

public class ProductController : Controller
{
    //
    // GET: /Product/
    public ActionResult Index()
    {
        return View(new Product{Id = 01, Price=100, ProductName="MyProduct", ProductDiscription="30 TeaBags in a pack"});
    }
}

查看

    @model CrudAppDemo.Models.Product

@{
    ViewBag.Title = "Products";
}

<h2>Products</h2>

<div class="row">
    <div class="col-md-4 ">

        <table class="table">

            <thead>
                <tr>
                    <td>@Html.DisplayNameFor(model => model.Name)</td>
                    <td>@Html.DisplayNameFor(model => model.Price)</td>
                    <td>@Html.DisplayNameFor(model => model.Description)</td>
                </tr>
            </thead>

            <tbody>
                    <tr>
                        <td>@Html.DisplayFor(model => model.Name)</td>
                        <td>@Html.DisplayFor(model => model.Price)</td>
                        <td>@Html.DisplayFor(model => model.Description)</td>                        
                    </tr>
            </tbody>

        </table>

    </div>
</div>

当我运行此代码时,我收到CS0411错误:

enter image description here

2 个答案:

答案 0 :(得分:1)

您的参数与模型中的参数不匹配。 你在模型中有ProductName,并且你试图访问不在模型中的Name,同样需要描述。

改为写下来。

<thead>
                <tr>
                    <td>@Html.DisplayNameFor(model => model.ProductName)</td>
                    <td>@Html.DisplayNameFor(model => model.Price)</td>
                    <td>@Html.DisplayNameFor(model => model. ProductDiscription)</td>
                </tr>
            </thead>

            <tbody>
                    <tr>
                        <td>@Html.DisplayFor(model => model.ProductName)</td>
                        <td>@Html.DisplayFor(model => model.Price)</td>
                        <td>@Html.DisplayFor(model => model. ProductDiscription)</td>                        
                    </tr>
            </tbody>

答案 1 :(得分:1)

您好像使用显示名称[Display(Name="Name")]作为您的媒体资源,而不是属性本身public String ProductName { get; set; }。尝试更改以使用属性名称。

  <td>@Html.DisplayNameFor(model => model.ProductName)</td>
  <td>@Html.DisplayNameFor(model => model.Price)</td>
  <td>@Html.DisplayNameFor(model => model.ProductDiscription)</td>
相关问题