Avatar of Bobmumm
Bobmumm
 asked on

C#, Valid ModelState fails .isValid

********************* SEARCH CONTROLLER *************************
    //
    // GET: /Search/Create

    public ActionResult Create()  { return View();  }

    //
    // POST: /Search/Create

    [HttpPost]
    public ActionResult Create(Search search)
    {
      search.Created = DateTime.Now;

      search. SearchSet = "test data";
      search. URLParameter  = 1432567389;
     
    if (ModelState.IsValid)
      {
         _db.Searchs.Add(search);
        _db.SaveChanges();
        return RedirectToAction("Index");
     
      }

     return View(search);
    }

************************* SEARCH CLASS ***********************

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace TalentProfile.Models
{
  public class Search
  {
    public int Id { get; set; }
      [Required]
    public int URLParameter { get; set; }
      [Required, MaxLength(50, ErrorMessage = "Client must be 50 characters or less")]
    public string Client { get; set; }
      [DataType(DataType.MultilineText), StringLength(150, ErrorMessage = "{0} must be {1} characters or less")]
    public string Notes { get; set; }
      [Required]
    public string SearchSet { get; set; }
      [Required]
    public DateTime Created { get; set; }
  }
}

If I run in debug all the fields in the class are properly set but it fails ModelState.isValid.  If I drill into the ModelState.isValid it is false.  Drilling down further I find the error “The SearchSet field is required”.
The SearchSet field is properly set to “test data”.  If I remove the ModelState.isValid check the save to the database succeeds.

Why am I getting the “field is required” error if the field contains valid data.

Thanks,

Bob


****** Updated Search Controller  and Create View ***************

//
// GET: /Search/Create

public ActionResult Create()
{
Search search = new Search();
search.SearchSet = "test Data";
return View(search); }

//
// POST: /Search/Create

[HttpPost]
public ActionResult Create(Search search)
{
search.Created = DateTime.Now;

search.URLParameter = 1435267836;

if (ModelState.IsValid)
{
_db.Searchs.Add(search);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(search);
}



In view put:  @Html.HiddenFor(model => model.SearchSet)
ASP.NET

Avatar of undefined
Last Comment
Bobmumm

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Bobmumm

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Your help has saved me hundreds of hours of internet surfing.
fblack61