When I click on the URL for add new post form in asp.net mvc. On page load the validations errors are displayed.
The errors are in red and should actually be prompted on submit button.
The user name is required
The title is required
Description is required
What I have tried:
Add Post Controller
public ActionResult AddPost(ForumPost post)
{
AdminObserver observer1 = new AdminObserver();
ActivityObserver observer2 = new ActivityObserver();
post.PostedOn = DateTime.Now;
if (!ModelState.IsValid)
{
return View(post);
}
using (AppDbContext db = new AppDbContext())
{
try
{
db.ForumPosts.Add(post);
db.SaveChanges();
}
catch (DbEntityValidationException e)
{
Console.WriteLine(e);
}
}
TempData["SM"] = "You have added a new Record!";
ForumNotifier notifier = new ForumNotifier();
notifier.Subscribe(observer1);
notifier.Subscribe(observer2);
notifier.Notify(post);
return View("AddPost", post);
}
Add Post form
<h2>AddPost</h2>
@if (TempData["SM"] != null)
{
<div class="alert alert-success">
@TempData["SM"]
</div>
}
@using (Html.BeginForm("AddPost","Home"))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>ForumPost</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
</div>
</div>
<h4>@ViewBag.Message</h4>
<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>
}