I am experiencing an issue where the model state is being applied to every form that exists on a single page. For example, if validation is not met e.g. the user doesn't complete a required field, then the message ' x field is required' is applied to every form after post back. The page has two 'different' (but exactly the same) forms on it
- comment reply form (sits after every comment and can occur x amount of times)
- new comment reply form (sits at the bottom of all the comments and exists once)
I am building up a comments section where foreach comment a user can leave a comment, this means that the comment reply form can exist x amount of times, if there are 10 comments then it will be on the page 10 times.
I have the following (scaled down for explanation purposes) code
Model
public string FullName { get; set; }
public string Email { get; set; }
public string Comment { get; set; }
View
@model BlogCommentsViewModel
// when this is pressed use js to show the form
<button type="button" id="form-toggle-btn" class="btn btn-md btn-primary-filled js-reply-comment-button">
<strong>REPLY <i class="fa fa-reply" aria-hidden="true"></i></strong>
</button>
@foreach (var item in Model.BlogComments)
{
///blog comment markup here
div class="reply-comment-form js-reply-comment-form">
@using (Html.BeginUmbracoForm<BlogCommentSurfaceController>("CreateComment", null, new { id = "reply-form"}))
{
@Html.AntiForgeryToken()
<div class="row">
<div class="col-sm-6">
<div class="form-group">
@Html.LabelFor(m => m.FullName)
@Html.TextBoxFor(m => m.FullName, new { placeholder = "Full Name", @class = "form-control" })
@Html.ValidationMessageFor(m => m.FullName)
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
@Html.LabelFor(m => m.Email)
@Html.TextBoxFor(m => m.Email, new { placeholder = "Email", @class = "form-control" })
@Html.ValidationMessageFor(m => m.Email)
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
@Html.LabelFor(m => m.Comment)
@Html.TextAreaFor(m => m.Comment, new { placeholder = "Message", @class = "form-control", @rows = 7 })
@Html.ValidationMessageFor(m => m.Comment)
</div>
</div>
<button type="submit" id="form-reply-submit" class="btn btn-md btn-primary-filled btn-form-submit">
<strong>POST REPLY</strong>
</button>
</div>
}
}
Controller
[HttpPost]
public ActionResult CreateComment(BlogCommentViewModel model)
{
if (!ModelState.IsValid || model == null)
return CurrentUmbracoPage();
return RedirectToCurrentUmbracoPage();
}
A form only shows when the 'post reply button is pressed, I use a small bit of JS with some CSS to show\hide a form' The problem I have, if validation fails it applies to all forms on the page. This is using jquery unobtrusive on the clientside
How can I restrict this to only the form that is interacted with ?
I read this which feels similar Multiple forms in MVC view: ModelState applied to all forms
Any help will be great.
Thanks