I'm trying to create tags for a blog project. I want the user to enter the tags, and then I want to display all the tags they enter. Right now, I'm struggling to just get that to work.
I keep getting a "System.NullReferenceException" in the view on the @Html.EditorFor
line:
@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>
}
This is the Controller ActionResult methods:
public ActionResult AddTag()
{
TagAdding tagg = new TagAdding();
tagg.Add = 0;
return View(tagg);
}
[HttpPost]
public ActionResult AddTag(TagAdding tagg)
{
tagg.Add++;
return View(tagg);
}
This is my model:
public class TagAdding
{
public Post Post { get; set; }
public List<Tag> Tag { get; set; } = new List<Tag>();
public int Add { get; set; }
}
How can I fix this?
Also, I don't even know if my code is the best way to achieve what I'm trying to do. I'd be more than happy to learn new things:)