Solved

C#, Valid ModelState fails .isValid

Posted on 2012-03-15
1
853 Views
Last Modified: 2012-03-16
********************* 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)
0
Comment
Question by:Bobmumm
1 Comment
 

Accepted Solution

by:
Bobmumm earned 0 total points
ID: 37730198
When the form is posted back to the POST action a Search object is created.  Created and URLParameter are DateTime and int fields are non-nullable and are set to 01/01/0001 and 0 by default.  SearchSet is a string whose default is null, thus the ModelState fails on SearchSet.  Drilling down into ModleState shows that it only checks the string fields (Client, Notes and SearchSet), Client and Notes are set in the view.  This is why you can set the DateTime and int but not the string fields in the POST action.  Passing the view a Search object with the SearchSet field set to a non-null value in the GET action and then exposing SearchSet with a @Html.HiddenFor  resolves the problem.  See updated post with the revised code.
0

Featured Post

Are your AD admin tools letting you down?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Reset asp.net login password 4 42
ASP.net Fit image buttons according to size of the screen 2 20
Problem to refer to value 8 49
mail.To.Add 5 26
Sometimes in DotNetNuke module development you want to swap controls within the same module definition.  In doing this DNN (somewhat annoyingly) swaps the Skin and Container definitions to the default admin selections.  To get around this you need t…
A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question