【发布时间】:2020-03-13 13:22:24
【问题描述】:
我有一个带有 Entity Framework 6 的简单 ASP.Net MVC 应用程序。
我有两个表:一个“联系人”列表(包含姓名、地址和电话号码)和第二个表,该表记录每个联系人的零个或多个“便笺”历史记录:
模型/Contact.cs:
public class Contact
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ContactId { get; set; }
public string Name { get; set; }
public string EMail { get; set; }
public string Phone1 { get; set; }
...
public virtual List<Note> Notes { get; set; }
}
模型/Note.cs:
public class Note
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int NoteId { get; set; }
public string Text { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime? Date { get; set; }
[ForeignKey("Contact")]
public int ContactId { get; set; }
public virtual Contact Contact { get; set; }
}
我在 Visual Studio 中做了一个“添加控制器”,它为“Index.cshtml”、“Details.cshtml”、“Edit.cshtml”和“Delete.cshtml”自动生成了“ContactsController.cs”和视图。所有自动生成的代码看起来都不错,并且运行良好。但它没有显示任何“注释”。
通过将以下内容添加到“Details.cshtml”和“Edit.cshtml”,我能够显示“注释”并添加编辑或删除注释的链接:
视图/联系人/Edit.cshtml:
@model ContactsApp.Models.Contact
...
<h4>Notes</h4>
<table class="table">
<tr>
<th>Date</th>
<th>Note</th>
<th> </th>
</tr>
@for (int i = 0; i < Model.Notes.Count(); i++)
{
<tr>
<td>@Html.DisplayFor(model => model.Notes[i].Date)</td>
<td>@Html.DisplayFor(model => model.Notes[i].Text)</td>
<td>
@Html.ActionLink("Edit Note", "EditNote", new { noteId = Model.Notes[i].NoteId }) |
@Html.ActionLink("Delete Note", "DeleteNote", new { noteId = Model.Notes[i].NoteId })
</td>
</tr>
}
</table>
我还创建了一个“EditNote.cshtml”视图...但我无法弄清楚如何从 ContactsController 调用它:
Controllers/ContactsController.cs:
// GET: Contacts/EditNote?noteId=3
public async Task<ActionResult> EditNote(int? noteId)
{
if (noteId == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Note note = await db.Contacts.Where(c => c.Notes.noteId == noteId);
if (note == null)
{
return HttpNotFound();
}
return View(note);
}
问:获取“Note”并将其传递到“EditNote”视图的正确 ASP.Net MV 语法是什么?
【问题讨论】:
标签: c# asp.net-mvc entity-framework-6