我正在尝试为一个博客项目创建标签。我希望用户输入标签,然后显示他们输入的所有标签。现在,我正在努力让它发挥作用。
我一直在@Html.EditorFor行的视图中得到一个"System.NullReferenceException“:
@model BlogNiKRaMu.Models.TagAdding
@{
ViewBag.Title = "AddTag";
var add = Model.Add;
}
<h2>AddTag</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Post</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@if (Model.Tag?.Count > 0)
{
<p>
Tags: @foreach (var item in Model.Tag)
{
@item.Name
})
</p>
}
**@Html.EditorFor(model => model.Tag[add].Name)**
@*<input type="Text" name="tagInput" value="Input Tag" />*@
<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>
}这是控制器ActionResult方法:
public ActionResult AddTag()
{
TagAdding tagg = new TagAdding();
tagg.Add = 0;
return View(tagg);
}
[HttpPost]
public ActionResult AddTag(TagAdding tagg)
{
tagg.Add++;
return View(tagg);
}这是我的模型:
public class TagAdding
{
public Post Post { get; set; }
public List<Tag> Tag { get; set; } = new List<Tag>();
public int Add { get; set; }
}我该如何解决这个问题呢?
此外,我甚至不知道我的代码是否是实现我想要做的事情的最佳方式。我非常乐意学习新的东西:)
发布于 2021-06-06 18:49:13
首先,如果您添加了您的模型(即BlogNiKRaMu.Models.TagAdding类),那么它将非常有用。
由于您使用EF Core标记了您的帖子,因此我假设问题出在您的实体类上,该实体类在Tags表的导航属性上没有默认值。然后,要加载和存储标记,您应该(自动)包含这些标记,或者至少相应地将它们存储在ITagService及其底层存储库的更新/保存方法(无论您想怎么调用它)中。
编辑1:感谢您对模型的更新。老实说,我不明白你在这里想做什么。也许你应该这样重新组织代码:
- `public Post Post { get; set; }` set from your view model
- `public string Name { get; set; }` set from the form data, and represents the tag name you want to add然后,
public ActionResult AddTag([FromBody]TagAddModel formContent)中的参数,并且在主体中,操作变得更加复杂:- Check if a tag with the same name exists in database
- If not, create that tag in a separate database table
- Then use the result of that "GetOrCreate" operation, which is of type `Tag`, and add it to the post, if not already present on that post
- Then persist everything to the database through the EF context免责声明:如果你完全不知道我在说什么,那么我建议你从比博客更简单的东西开始。在开发软件时,拥有一个有趣的可维护项目是最重要的事情,你真的需要设计策略来使你的项目工作。
无论如何,祝你好运,希望它能帮上忙!
https://stackoverflow.com/questions/67858177
复制相似问题