Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在单个视图上创建和显示模型数据?_C#_Asp.net_Asp.net Mvc - Fatal编程技术网

C# 如何在单个视图上创建和显示模型数据?

C# 如何在单个视图上创建和显示模型数据?,c#,asp.net,asp.net-mvc,C#,Asp.net,Asp.net Mvc,目标是能够从同一视图中的模型创建和显示无序列表项 这就是我目前所拥有的 型号: Notes.cs namespace NoteTaking.Models { public class Notes { public int Id { get; set; } public string Text { get; set; } public float Time { get; set; } } public class M

目标是能够从同一视图中的模型创建和显示无序列表项

这就是我目前所拥有的 型号: Notes.cs

namespace NoteTaking.Models
{
    public class Notes
    {
        public int Id { get; set; }
        public string Text { get; set; }
        public float Time { get; set; }
    }

    public class MyDbContext : DbContext
    {
        public MyDbContext() : base("Notes")
        {

        }

        public DbSet<Notes> Notes { get; set; }
    }
}
Index.cshtml

@model NoteTaking.Models.Notes

@{
    ViewBag.Title = "Index";
}

<div class="jumbotron"></div>

@using (Html.BeginForm())
{
    @Html.EditorFor(model => model.Text)
    <input type="submit" value="Create" class="btn btn-default" />
}

<div>
    <h2>Notes</h2>
    @foreach (var d in Model.Text)
    {
        <ul>
            <li>
                @d
            </li>
        </ul>
    }
</div>
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title></title>
</head>
<body>
    <div>
        @{ Html.RenderPartial("Notes"); }
    </div>
</body>
</html>
我知道我会遇到一个编译错误,我已经尝试通过使用IEnumerable等多种方法来解决这个问题,但这不允许我使用@Html.EditorFor


我很困惑。

这是因为您正在您的数据库中迭代IEnumerable类型

   @for (var d in Model.Text)
    {
        <ul>
            <li>
                @d
            </li>
        </ul>
    }
尝试将其设置为可枚举类型:

@model IEnumerable<NoteTaking.Models.Notes>

/*
    Your codes here
*/
编辑:

现在我明白你的意思了。您可能希望在同一页面上显示新添加/编辑的实体。现在,你可以这样做:

@model NoteTaking.Models.Notes

    @{
        ViewBag.Title = "Index";
    }

    <div class="jumbotron"></div>

    @using (Html.BeginForm())
    {
        @Html.EditorFor(model => model.Text)
        <input type="submit" value="Create" class="btn btn-default" />
    }

    <div>
        <h2>Notes</h2>
        @foreach (var d in Model.ToList())
        {
            <ul>
                <li>
                    @d.Text
                </li>
            </ul>
        }
    </div>

您的索引方法正在返回一组注释

return View(db.Notes.ToList());
因此,这种观点应该是正确的

@model IEnumerable<NoteTaking.Models.Notes>
@using (Html.BeginForm())
{
  @Html.EditorFor(m => m)
  <input type="submit" value="Create" class="btn btn-default" />
}
public ActionResult Index(IEnumerable<Notes> notes)
你的POST方法应该是

@model IEnumerable<NoteTaking.Models.Notes>
@using (Html.BeginForm())
{
  @Html.EditorFor(m => m)
  <input type="submit" value="Create" class="btn btn-default" />
}
public ActionResult Index(IEnumerable<Notes> notes)
在控制器中

public ActionResult Index()
{
  NotesVM model = new NotesVM();
  model.NewNote = new Notes();
  model.NoteList = db.Notes.ToList();
  return View(model);
}
在我看来

@model NotesVM
....
@using (Html.BeginForm())
{
  @Html.EditorFor(m => m.NewNote.Text)
  <input type="submit" value="Create" class="btn btn-default" />
}
....
<ul>
  @foreach (var d in Model.NotesList)
  {
    <li>@d.Text</li>
  }
</ul>

注:我还建议为类注释本身创建一个视图模型,以便您可以使用局部视图添加验证属性。您可以将一个模型作为一个模型集合,这是一个非常粗略的示例,但我模拟了一些使用EF6和快速代码优先数据库工作的模型

它不是世界上最快的东西,但演示了如何从EntityFramework返回结果集合,该集合作为视图的模型绑定到视图。以及如何添加新项目。对此可以做很多调整

一个这样的调整:返回调用了AsNoTracking的模型,这样它们就不会被跟踪,无论如何也不能跟踪accross回发

观点

/Views/Home/Index.cshtml /视图/Shared/NewNote.cshtml /Views/Shared/Notes.cshtml

@model System.Data.Entity.DbSet<NotesExample.Models.Note>
@{
    MyDbContext context = new MyDbContext();
    int noteCount = Model.Count();
    var notes = Model.ToList();
}
@for (int i = 0; i < noteCount || (notes.Count == 0 && i == 0); ++i)
{
    if (notes.Count == 0 || i == notes.Count - 1)
    {
        //Add New Note
        Html.RenderPartial("NewNote", new NotesExample.Models.Note());
    }
    else
    {
        //Render Exising Notes
        var note = notes[i];
        <div>
            <h3>Note ID: @note.Id</h3>
            <h3>Text: @note.Text</h3>
            <h3>Time (ticks): @note.Time</h3>
        </div>
    }
}
控制器

public class HomeController : Controller
{
    MyDbContext data = new MyDbContext();

    public ActionResult Index()
    {
        var notes = data.Notes;
        return View(notes);
    }

    public ActionResult AddNewNote(Models.Note model)
    {
        data.Notes.Add(model);
        data.SaveChanges();
        var notes = data.Notes;
        return Redirect("~/");
    }
}
模型

模型EF配置类

public class NoteConfig : EntityTypeConfiguration<Note>
{
    public NoteConfig()
    {
        this.HasKey(p => p.Id).Property(p1 => p1.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    //this.HasRequired(p => p.Text);
     }
}
DBContext

public class MyDbContext : DbContext
{
    #region DBSet
    public DbSet<Models.Note> Notes { get; set; }
    #endregion

    #region Constructor
    public MyDbContext()
        : base("Data Source=" + HttpContext.Current.Server.MapPath("~/Bin/NotesExample.sdf"))
    {
        this.Configuration.AutoDetectChangesEnabled = true;
        this.Configuration.LazyLoadingEnabled = true;
        this.Configuration.ValidateOnSaveEnabled = true;
        this.Database.CreateIfNotExists();
    }
    #endregion

    #region Methods
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        NoteConfig noteConfig = new NoteConfig();
        modelBuilder.Configurations.Add(noteConfig);
        base.OnModelCreating(modelBuilder);
    }
    #endregion
}
Index.cshtml

@model NoteTaking.Models.Notes

@{
    ViewBag.Title = "Index";
}

<div class="jumbotron"></div>

@using (Html.BeginForm())
{
    @Html.EditorFor(model => model.Text)
    <input type="submit" value="Create" class="btn btn-default" />
}

<div>
    <h2>Notes</h2>
    @foreach (var d in Model.Text)
    {
        <ul>
            <li>
                @d
            </li>
        </ul>
    }
</div>
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title></title>
</head>
<body>
    <div>
        @{ Html.RenderPartial("Notes"); }
    </div>
</body>
</html>
Notes.cshtml

@model System.Data.Entity.DbSet<NotesExample.Models.Note>
@{
    MyDbContext context = new MyDbContext();
    int noteCount = Model.Count();
    var notes = Model.ToList();
}
@for (int i = 0; i < noteCount || (notes.Count == 0 && i == 0); ++i)
{
    if (notes.Count == 0 || i == notes.Count - 1)
    {
        //Add New Note
        Html.RenderPartial("NewNote", new NotesExample.Models.Note());
    }
    else
    {
        //Render Exising Notes
        var note = notes[i];
        <div>
            <h3>Note ID: @note.Id</h3>
            <h3>Text: @note.Text</h3>
            <h3>Time (ticks): @note.Time</h3>
        </div>
    }
}
NewNote.cshtml

@model NotesExample.Models.Note
@using (Html.BeginForm("AddNewNote", "Home"))
{
    <div>
    <label>New Note Text:</label>@Html.TextBoxFor(p => p.Text)
    </div>
    <input type="submit" name="AddNewNote" value="Add New Note" />
}

我已经编辑了你的标题。请看,如果一致意见是否定的,他们就不应该这样做。当我使用@model IEnumerable时,我最终得到了@Html.EditorFormodel=>model.Text的编译错误。关于怎么做有什么建议吗?尽管你的问题措辞不同,但看看你的查看代码,我发现提交按钮文本是Create,所以你的意思可能是显示一个集合并创建一个新项目?在这种情况下,我同意你完全不同的要求。这个问题的题目很矛盾。但是,他想要实现的目标仍然是可能的。只是在他的问题和问题的细节上有一些不一致,所以我想我离得越来越近了,但是在你更改HomeController索引[post]方法之后,我返回了一个错误。“db.Notes.Addnotes;”行说它有一些无效的参数。此外,我计划在将来为视图添加一个计时器。我正在做的这个方法会使将计时器经过的时间浮点添加到模型中变得复杂吗?@LouisMichael,是的,但很抱歉,你编辑的答案中没有代码是的!我想创建一个新项目,并在同一视图中显示它。抱歉搞混了,你们真是帮了大忙。我将编辑我的问题上面。我迷失在这个,忘记了它是一个视图。。。我稍后再试。
@model NotesExample.Models.Note
@using (Html.BeginForm("AddNewNote", "Home"))
{
    <div>
    <label>New Note Text:</label>@Html.TextBoxFor(p => p.Text)
    </div>
    <input type="submit" name="AddNewNote" value="Add New Note" />
}