Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4069834
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T16:33:01+00:00 2026-05-20T16:33:01+00:00

I have a view with model BlogPostViewModel : public class BlogPostViewModel { public BlogPost

  • 0

I have a view with model BlogPostViewModel:

public class BlogPostViewModel
{
    public BlogPost BlogPost { get; set; }
    public PostComment NewComment { get; set; }
}

This view is rendered when action method BlogPost is hit. The view displays information regarding the blog post as well as a list of comments on the blog post by iterating over Model.BlogPost.PostComments. Below that I have a form allowing users to post a new comment. This form posts to a different action AddComment.

    [HttpPost]
    public ActionResult AddComment([Bind(Prefix = "NewComment")] PostComment postComment)
    {
        postComment.Body = Server.HtmlEncode(postComment.Body);
        postComment.PostedDate = DateTime.Now;
        postCommentRepo.AddPostComment(postComment);
        postCommentRepo.SaveChanges();
        return RedirectToAction("BlogPost", new { Id = postComment.PostID });
    }

My problem is with validation. How do I validate this form? The model of the view was actually BlogPostViewModel. I’m new to validation and am confused. The form uses the strongly-typed helpers to bind to the NewComment property of BlogPostViewModel and I included the validation helpers as well.

@using (Html.BeginForm("AddComment", "Blog")
{
    <div class="formTitle">Add Comment</div>
    <div>
        @Html.HiddenFor(x => x.NewComment.PostID) @* This property is populated in the action method for the page. *@
        <table>
            <tr>
                <td>
                    Name:
                </td>
                <td>
                    @Html.TextBoxFor(x => x.NewComment.Author)
                </td>
                <td>
                    @Html.ValidationMessageFor(x => x.NewComment.Author)
                </td>
            </tr>
            <tr>
                <td>
                    Email:
                </td>
                <td>
                    @Html.TextBoxFor(x => x.NewComment.Email)
                </td>
                <td>
                    @Html.ValidationMessageFor(x => x.NewComment.Email)
                </td>
            </tr>
            <tr>
                <td>
                    Website:
                </td>
                <td>
                    @Html.TextBoxFor(x => x.NewComment.Website)
                </td>
                <td>
                    @Html.ValidationMessageFor(x => x.NewComment.Website)
                </td>
            </tr>
            <tr>
                <td>
                    Body:
                </td>
                <td>
                    @Html.TextAreaFor(x => x.NewComment.Body)
                </td>
                <td>
                    @Html.ValidationMessageFor(x => x.NewComment.Body)
                </td>
            </tr>
            <tr>
                <td>
                </td>
                <td>
                    <input type="submit" value="Add Comment" />
                </td>
            </tr>
        </table>
    </div>
}

How in the AddComment action method do I implement validation? When I detect Model.IsValid == false then what? What do I return? This action method is only binding to the PostComment property of the pages initial BlogPostViewModel object because I don’t care about any other properties on that model.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T16:33:02+00:00Added an answer on May 20, 2026 at 4:33 pm

    You need to repopulate the model and send to view. However, you don’t need to do this by hand, you can use action filters.

    see:

    http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx#prg

    Specifically:

    public abstract class ModelStateTempDataTransfer : ActionFilterAttribute
    {
        protected static readonly string Key = typeof(ModelStateTempDataTransfer).FullName;
    }
    
    public class ExportModelStateToTempData : ModelStateTempDataTransfer
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            //Only export when ModelState is not valid
            if (!filterContext.Controller.ViewData.ModelState.IsValid)
            {
                //Export if we are redirecting
                if ((filterContext.Result is RedirectResult) || (filterContext.Result is RedirectToRouteResult))
                {
                    filterContext.Controller.TempData[Key] = filterContext.Controller.ViewData.ModelState;
                }
            }
    
            base.OnActionExecuted(filterContext);
        }
    }
    
    public class ImportModelStateFromTempData : ModelStateTempDataTransfer
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            ModelStateDictionary modelState = filterContext.Controller.TempData[Key] as ModelStateDictionary;
    
            if (modelState != null)
            {
                //Only Import if we are viewing
                if (filterContext.Result is ViewResult)
                {
                    filterContext.Controller.ViewData.ModelState.Merge(modelState);
                }
                else
                {
                    //Otherwise remove it.
                    filterContext.Controller.TempData.Remove(Key);
                }
            }
    
            base.OnActionExecuted(filterContext);
        }
    }
    

    Usage:

    [AcceptVerbs(HttpVerbs.Get), ImportModelStateFromTempData]
    public ActionResult Index(YourModel stuff)
    {
        return View();
    }
    
    [AcceptVerbs(HttpVerbs.Post), ExportModelStateToTempData]
    public ActionResult Submit(YourModel stuff)
    {
        if (ModelState.IsValid)
        {
            try
            {
                //save
            }
            catch (Exception e)
            {
                ModelState.AddModelError(ModelStateException, e);
            }
        }
    
        return RedirectToAction("Index");
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a view model - public class MyViewModel { public int id{get;set;}; Public
In the world of MVC I have this view model... public class MyViewModel{ [Required]
I have a view model that has a property that looks like this Property
I have a view model with a collection of other objects in it. public
Using an MVVM approach to WPF, I have a view model class called SubButton
A simple question: I have a Model-View-Controller setup, with Models accessing a SQL database.
I have a view user control that can post form. This control can be
I have a view model that needs to encapsulate a couple of many-to-many relationships.
I have a view model with a property Fields which is an ObservableCollection<FieldVM> .
I have a simple .Net enum. I also have a view model object which

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.