Solved

C#, Valid ModelState fails .isValid

Posted on 2012-03-15
1
831 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

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

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…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

759 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now