Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model state not valid

So I have a view called index that lays out all of the threads in my database. Then inside that view I'm loading all the comments on the threads. When I call on my form that is supposed to create a new comment it keeps telling me that my model state is invalid. It tells me that it cannot convert from type string to type profile or comment or tag. Originally I had this as my code:

 public ActionResult AddComment(Thread thread, string commentBody)
    {
        if (ModelState.IsValid)
        {
            _repository.AddComment(thread, comment);
            TempData["Message"] = "Your comment was added.";
            return RedirectToAction("Index");
        }

Then I changed it to this:

 public ActionResult AddComment(Thread thread, string commentBody)
    {
        Profile profile = _profileRepository.Profiles.FirstOrDefault(x => x.Id ==       thread.ProfileId);
        Tag tag = _tagRepository.Tags.FirstOrDefault(t => t.Id == thread.TagId);
        thread.ThreadTag = tag;
        thread.Profile = profile;
        Comment comment = new Comment()
                              {
                                  CommentBody = commentBody,
                                  ParentThread = thread
                              };
        if (ModelState.IsValid)
        {
            _repository.AddComment(thread, comment);
            TempData["Message"] = "Your comment was added.";
            return RedirectToAction("Index");
        }

This still tells me that my model state is invalid. How do I get it so that it will not try to change the state?

Also here is the form that is being used to call this action:

@using(Html.BeginForm("AddComment", "Thread", mod))
            {
                <input type="text" name="AddComment" id="text" />
                <input type="submit" value="Save"/>
            }

In the instance of code above mod is the model which is a thread. And as requested here is everything inside of thread:

 public Thread()
    {
        this.ChildComments = new HashSet<Comment>();
    }

    public int Id { get; set; }
    public string TopicHeader { get; set; }
    public string TopicBody { get; set; }
    public Nullable<int> UpVotes { get; set; }
    public Nullable<int> DownVotes { get; set; }
    public int ProfileId { get; set; }
    public int TagId { get; set; }

    public virtual Profile Profile { get; set; }
    public virtual ICollection<Comment> ChildComments { get; set; }
    public virtual Tag ThreadTag { get; set; }

And finally the comment class:

 public partial class Comment
{
    public int Id { get; set; }
    public string CommentBody { get; set; }
    public int UpVotes { get; set; }
    public int DownVotes { get; set; }

    public virtual Thread ParentThread { get; set; }
}
like image 831
Robert Young Avatar asked Mar 08 '12 03:03

Robert Young


People also ask

Why is model state invalid in MVC?

That's because an error exists; ModelState. IsValid is false if any of the properties submitted have any error messages attached to them. What all of this means is that by setting up the validation in this manner, we allow MVC to just work the way it was designed.

How do I know if a model is valid or not?

Below the Form, the ModelState. IsValid property is checked and if the Model is valid, then the value if the ViewBag object is displayed using Razor syntax in ASP.Net MVC.

For which model state is valid validate?

Model state Model validation occurs after model binding and reports errors where data doesn't conform to business rules. For example, a 0 is entered in a field that expects a rating between 1 and 5. Web API controllers don't have to check ModelState. IsValid if they have the [ApiController] attribute.

What is model state in C#?

ModelState is a property of a Controller instance, and can be accessed from any class that inherits from Microsoft. AspNetCore. Mvc. Controller. The ModelState has two purposes: to store and submit POSTed name-value pairs, and to store the validation errors associated with each value.


1 Answers

Use the code below to iterate through the errors. Then you can see what field and what object is failing on validation. And then you can go from there. Just looking at the IsValid property is not going to give enough information.

var errors = ModelState.Values.SelectMany(v => v.Errors);

And then loop through the errors.

like image 144
dean oliver Avatar answered Oct 04 '22 22:10

dean oliver