У меня возникла проблема с отправкой родительского идентификатора в дочерний идентификатор, даже если я это сделаю, я хочу отображать дочерние данные только определенного родителя. В моем коде Список является родительским, а Примечания — дочерними. Когда я создаю список, я перенаправляюсь на индексную страницу заметок (другой контроллер) вместе с идентификатором, но во всех списках я вижу одни и те же заметки. Я использую TempData в NotesController, чтобы сохранить этот идентификатор.
Контроллер списка:
//Index
public ActionResult Index()
{
return View(db.Lists.ToList());
}
//Create
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ListViewModel lists)
{
if (ModelState.IsValid)
{
Lists list = new Lists();
list.CreationDate = DateTime.Now;
list.ListName = lists.ListName;
db.Lists.Add(list);
db.SaveChanges();
int? idFromView = list.Id;
return RedirectToAction("Index", "NotesInLists", new { id = idFromView });
}
return View(lists);
}
Примечания Контроллер:
//Index
public ActionResult Index(int? id)
{
TempData["idFromView"] = id;
return View(db.NotesInLists.ToList());
}
//Create
public ActionResult CreateWithtext()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateWithtext(NoteTagViewModel notesInList)
{
if (ModelState.IsValid)
{
List<string> TagsList = notesInList.TagsList.Split(',').ToList();
NotesInList note = new NotesInList();
int tempDataId = (int)TempData["idFromView"];
note.CreationDate = DateTime.Now;
note.ListName = notesInList.ListName;
note.TextDescription = notesInList.TextDescription;
note.listID = tempDataId;
db.NotesInLists.Add(note);
db.SaveChanges();
//saving tags
foreach (var item in TagsList)
{
Tags tag = new Tags();
tag.CreationDate = DateTime.Now;
tag.TagName = item;
tag.Note_Id = note.Id;
db.Tags.Add(tag);
}
db.SaveChanges();
return RedirectToAction("Index", new { id = tempDataId });
}
return View(notesInList);
}
Здесь, в этом NotesController, я также сохраняю теги, и он работает нормально, но основная проблема связана со списком. Также использую ViewModels, но меня это пока не волнует. Если я попытаюсь получить доступ к списку, используя
Lists list = new List();
Я до сих пор не могу проверить и сравнить этот идентификатор с этим идентификатором списка, он выдает исключение.
Модель списка:
namespace NoteBlocks.Models
{
public class Lists
{
public int Id { get; set; }
[Required]
[Display(Name = "List Name")]
public string ListName { get; set; }
[Display(Name = "Creation Date")]
public DateTime? CreationDate { get; set; }
[Display(Name = "Last Updated")]
public DateTime? UpdateDate { get; set; }
}
}
Список ViewModel:
namespace NoteBlocks.ViewModels
{
public class ListViewModel
{
public int Id { get; set; }
[Required]
[Display(Name = "List Name")]
public string ListName { get; set; }
[Display(Name = "Creation Date")]
public DateTime? CreationDate { get; set; }
[Display(Name = "Last Updated")]
public DateTime? UpdateDate { get; set; }
}
}
Примечания Модель:
namespace NoteBlocks.Models
{
public class NotesInList
{
public int Id { get; set; }
[Required]
[Display(Name = "List Name")]
public string ListName { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Creation Date")]
public DateTime? CreationDate { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Last Updated")]
public DateTime? UpdateDate { get; set; }
public string customFile { get; set; }
[Display(Name = "Enter Note Content")]
public string TextDescription { get; set; }
public Lists List { get; set; }
public int listID { get; set; }
}
}
Примечания ViewModel:
namespace NoteBlocks.Models
{
public class NoteTagViewModel
{
public int NoteId { get; set; }
[Required]
[Display(Name = "List Name")]
public string ListName { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Creation Date")]
public DateTime? CreationDate { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Last Updated")]
public DateTime? UpdateDate { get; set; }
public string customFile { get; set; }
[Display(Name = "Enter Note Content")]
public string TextDescription { get; set; }
//multiple tags
public string TagsList { get; set; }
public Lists List { get; set; }
public int ListId { get; set; }
}
}
Создал внешний ключ, но он не работает.
HTML — индекс списка
@model IEnumerable<NoteBlocks.Models.Lists>
@{
ViewBag.Title = "List";
//ViewBag.Id = model.Lists.Id;
}
<h2>List</h2>
<p>
@Html.ActionLink(" Create New List", "Create")
</p>
<table class = "table">
<tr>
<th>
@Html.DisplayNameFor(model => model.ListName)
</th>
<th>
@Html.DisplayNameFor(model => model.CreationDate)
</th>
<th>
@Html.DisplayNameFor(model => model.UpdateDate)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
//using ActionLink to open list of notes for that particular List
//and passing particular List ID from here if already created
@Html.ActionLink(item.ListName, "Index", "NotesInLists", new { id = item.Id }, null)
@*@TempData.Peek("tempDataId")*@
</td>
<td>
@Html.DisplayFor(modelItem => item.CreationDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.UpdateDate)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
HTML — создание списка
@model NoteBlocks.Models.Lists
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class = "form-horizontal">
<h4>List</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class = "form-group">
@Html.LabelFor(model => model.ListName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class = "col-md-10">
@Html.EditorFor(model => model.ListName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ListName, "", new { @class = "text-danger" })
</div>
</div>
<div class = "form-group">
@Html.LabelFor(model => model.CreationDate, htmlAttributes: new { @class = "control-label col-md-2" })
<div class = "col-md-10">
@Html.EditorFor(model => model.CreationDate, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.CreationDate, "", new { @class = "text-danger" })
</div>
</div>
<div class = "form-group">
@Html.LabelFor(model => model.UpdateDate, htmlAttributes: new { @class = "control-label col-md-2" })
<div class = "col-md-10">
@Html.EditorFor(model => model.UpdateDate, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.UpdateDate, "", new { @class = "text-danger" })
</div>
</div>
<div class = "form-group">
<div class = "col-md-offset-2 col-md-10">
<input type = "submit" value = "Create" class = "btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
HTML — указатель заметок
@model IEnumerable<NoteBlocks.Models.NotesInList>
@{
ViewBag.Title = "List Notes";
}
<h2>List Notes</h2>
<p id = "buttonsInPTag">
<button type = "button" class = "btn btn-primary" id = "addButton1"><span class = "glyphicon glyphicon-plus">@Html.ActionLink(" Create Textual Note", "CreateWithtext")</span></button>
<button type = "button" class = "btn btn-primary" id = "addButton2"><span class = "glyphicon glyphicon-plus">@Html.ActionLink(" Create Note from Document", "CreateWithDoc")</span></button>
<button type = "button" class = "btn btn-primary" id = "addButton3"><span class = "glyphicon glyphicon-plus">@Html.ActionLink(" Create Image Note", "CreateWithImage")</span></button>
<button type = "button" class = "btn btn-primary" id = "addButton4"><span class = "glyphicon glyphicon-plus">@Html.ActionLink(" Create Audio / Video Note", "CreateWithMedia")</span></button>
</p>
<table class = "table">
<tr>
<th>
@Html.DisplayNameFor(model => model.ListName)
</th>
<th>
@Html.DisplayNameFor(model => model.CreationDate)
</th>
<th>
@Html.DisplayNameFor(model => model.UpdateDate)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.ListName)
</td>
<td>
@Html.DisplayFor(modelItem => item.CreationDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.UpdateDate)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
@Html.ActionLink("Details", "Details", new { id = item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
</table>
HTML — заметки CreateWithText
@model NoteBlocks.Models.NoteTagViewModel
@{
ViewBag.Title = "Create Note with Text";
}
<h2>Create Note with Text</h2>
@using (Html.BeginForm("CreateWithText", "NotesInLists", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class = "form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class = "form-group">
@Html.LabelFor(model => model.ListName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class = "col-md-10">
@Html.EditorFor(model => model.ListName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ListName, "", new { @class = "text-danger" })
</div>
</div>
<div class = "form-group">
@Html.LabelFor(model => model.TextDescription, htmlAttributes: new { @class = "control-label col-md-2" })
<div class = "col-md-10">
<textarea cols = "50" rows = "12" class=form-control id = "TextDescription" name = "TextDescription"></textarea>
@Html.ValidationMessageFor(model => model.TextDescription, "", new { @class = "text-danger" })
</div>
</div>
<div class = "form-group">
@Html.Label("Tags", htmlAttributes: new { @class = "control-label col-md-2" })
<div class = "col-md-10">
<input type = "text" id = "tagsField" name = "tagsField" class=form-control data-role = "tagsinput" />
<input type = "hidden" name = "TagsList" id = "TagsList" />
</div>
</div>
<div class = "form-group">
<div class = "col-md-offset-2 col-md-10">
<input type = "submit" value = "Create" class = "btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section scripts
{
<script>
$(document.body).on('focusout', '.bootstrap-tagsinput input', () => {
let array = $('#tagsField').tagsinput('items');
$("#TagsList").val(array);
})
</script>
}
Я застрял в этой точке. Пожалуйста, направляйте. p.s. используя первый подход кода.
🤔 А знаете ли вы, что...
C# поддерживает LINQ (Language Integrated Query) для удобного запроса и обработки данных.
К запросу, который получает заметки в вашем действии Index контроллера заметок, не применяется фильтр.
Я думаю добавить оператор куда;
.Where(x=>x.listID == id)
решит вашу проблему.
//Index
public ActionResult Index(int? id)
{
TempData["idFromView"] = id;
return View(db.NotesInLists/*.Where(x=>x.listID == id)*/.ToList());
}