【问题标题】:Unable to display data using EditorFoModel html helper in MVC无法在 MVC 中使用 EditorFoModel html 助手显示数据
【发布时间】:2017-02-06 08:25:21
【问题描述】:

我想在复选框旁边显示手机名称。 因此,我将以下代码与 EditorForModel 一起使用,但它仅在 12 中呈现。我不明白为什么它显示 12 而不是手机名称。

我使用 Ado.net 实体模型从数据库表 Mobile 生成模型类。所以我有一个名为 Mobile.cs 的模型类

    namespace MvcDropdown.Models
    {
    using System;
    using System.Collections.Generic;

    public partial class Mobile
    {
        public int Model { get; set; }
        public string Type { get; set; }
        public string Cost { get; set; }
        public Nullable<bool> IsSelected { get; set; }
    }
}

在 HomeController 中,我有一个动作方法

public ActionResult checkboxfun()
        {
            GadgetsContext gc = new GadgetsContext();
            return View(gc.Mobiles);
        }

现在我通过将视图命名为 Mobile 来使用编辑器模板,如下所示。

@model MvcDropdown.Models.Mobile

@Html.HiddenFor(m=>m.Model)
@Html.HiddenFor(m=>m.Type)

@Html.EditorFor(m=>m.IsSelected)
@Html.DisplayFor(m=>m.Type)

在 checkboxfun 视图中,我有以下代码。

@model IEnumerable<MvcDropdown.Models.Mobile>

@using(Html.BeginForm())
{
@Html.EditorForModel()     
    <br />
    <input type="submit" value="submit" />
}

现在我无法查看数据库中的数据。

【问题讨论】:

  • 您的编辑器模板是否名为Mobile.cshtml 并位于/Views/Shared/EditorTemplates 文件夹中?
  • 您遇到了哪个错误?您的编辑器模板使用MvcDropdown.Models.Mobile 作为其模型,但视图页面使用IEnumerable&lt;MvcDropdown.Models.Mobile&gt;。此外,如果MobilesDbSetMobile,您可以尝试返回IEnumerable 集合:return View(gc.Mobiles.ToList());
  • @TetsuyaYamamoto。 EditorForModel() 接受单个对象和集合,.ToList() 不是必需的
  • @Tetsuya 我无法显示手机名称和名称复选框,它只显示 12 和提交按钮
  • @StephenMuecke 编辑器模板位于 /Views/Home/EditorTemplates

标签: c# asp.net-mvc asp.net-mvc-4 editorformodel


【解决方案1】:

您生成 1 2 因为该方法没有找到匹配的模板,并且将默认呈现模型的第一个属性的值(在您的情况下,您在集合中有两个项目 Model = 1 和 @987654323 @。

您的模板必须命名为Mobile.cshtml 以匹配类名,并且位于/Views/Shared/EditorTemplates/Views/yourControllerName/EditorTemplates(在您的情况下为/Views/Home/EditorTemplates)文件夹中

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-08
    • 2016-07-10
    • 2017-02-25
    • 2015-03-03
    • 2011-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多