ASP.NET MVC validation problem - data is not poste

2019-08-30 06:24发布

问题:

I have the following class:

public class NewCommentClass
{
    public string ActionName { get; set; }
    public object RouteValues { get; set; }
    [Required(ErrorMessage = "Comment Required")]
    public string Comment { get; set; }
    public int? CommentParentID { get; set; }
}

following code in view:

        NewCommentClass newCommentClass = new NewCommentClass() { ActionName = "PostComment", RouteValues = new { id = ideaItem.Ideas.IdeaID } };
        Html.RenderPartial("~/Views/Shared/NewComment.ascx", newCommentClass);

and NewComment.ascx:

    <% @ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<NEOGOV_Ideas.Models.NewCommentClass>" %>
....
    <div class="comment-new-container">
        <div class="grid_1 alpha item-sidebar">
            <p style="padding-top: 0.5em">
                <a href="#">
                    <img src="<% = userAvatar %>" class="profile-photo" alt="Your Profile Picture" width="48"
                        height="48" /></a>
            </p>
        </div>
        <div class="grid_8 omega">
            <div class="comment-body">
                <% using (Html.BeginForm(Model.ActionName, "Home", Model.RouteValues, FormMethod.Post, new { id = "FormAddComment", name = "FormAddComment" }))
                   { %>
                <fieldset>
                    <% = Html.TextAreaFor(model => model.Comment, htmlAttributes)%>
                    <% = Html.ValidationMessageFor(model=>model.Comment) %>
                    <input type="submit" value="<% = postButtonTitle %>" class="small blue awesome noborder" />
                </fieldset>
                <%} %>
            </div>
        </div>
        <div class="clear">
        </div>
    </div>

and following post method in controller:

     public ActionResult PostComment(int id, string Comment, int? CommentParentID, string referrerUrl)
        {
...
}

but this validation does not work correctly. If I enter data to textarea and click on "Submit" - all ok But If I just click on "Submit" without data inside - got error message (it's correct), but when I enter data to textarea after this action - error message is hidden, but form is not submited!. If I add Html.ValidationSummary(true) - I one label is hidden, but second is shown. Why so strange behaviour?

回答1:

In your Html.BeginForm() command, you create an HtmlAttribute object, and you use it to set the name and id of your textarea to FormAddComment. Because this is the only field in the form, you would need to change your method signature as follows:

[HttpPost]
public ActionResult PostComment(string FormAddComment)

Your current signature doesn't receive anything from the posted form. If you use Fiddler or a similar tool to inspect what is being posted, you will see FormAddComment=[whatever was typed into the textarea] as the body of the POST sent from your browser.