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 8414973
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T01:18:37+00:00 2026-06-10T01:18:37+00:00

Am I the only one having this problem or I am doing it in

  • 0

Am I the only one having this problem or I am doing it in totally wrong direction.

I have a View passing DateTime value:

<div class="control-group">
@Html.Label("Appointment date", null, new { @class = "control-label" })
<div class="controls">
    <div class="input-append">
        @Html.TextBoxFor(model => model.Appointment.Client_PreferredDate, new { @readonly = "readonly" })
        <span class="add-on margin-fix"><i class="icon-th"></i></span>
    </div>
    <p class="help-block">
        @Html.ValidationMessageFor(model => model.Appointment.Client_PreferredDate)
    </p>
</div>

The values are passed into the Controller action ( I can see the value, and I know it is giving the format that is not DateTime, i.e. it is going to be in dd-MM-yyyy). Then in the Controller I will reformat it.

[HttpPost]
public ActionResult RequestAppointment(General_Enquiry model, FormCollection fc)

{       
    model.Appointment.Client_PreferredDate = Utilities.formatDate(fc["Appointment.Client_PreferredDate"]);
    ModelState.Remove("Appointment.Client_PreferredDate");

try
{
    if (ModelState.IsValid)
    {
        model.Branch_Id = Convert.ToInt32(fc["selectedBranch"]);
        model.Appointment.Branch_Id = Convert.ToInt32(fc["selectedBranch"]);
        db.General_Enquiry.AddObject(model);
        db.SaveChanges();
        return RedirectToAction("AppointmentSuccess", "Client");
    }
}
catch (Exception e)
{
    Debug.WriteLine("{0} First exception caught.", e);
    Debug.WriteLine(e.InnerException);
    ModelState.AddModelError("", e);
}

return View(model);

}

The best I can do is to use ModelState.Remove(), which I feel really uncomfortable with. I suspect that when my Model is passed from the View to Controller, the ModelState is already set to Invalid before I can do anything in the Controller. Any ideas?

If I call the ModelState.Remove() everything went smoothly, the DateTime is accepted by SQL server database.

If at least I can update or ‘refresh’ ModelState at any point it’ll fix my problem.

Cheers.

  • 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-06-10T01:18:38+00:00Added an answer on June 10, 2026 at 1:18 am

    I’d recommend you using a view model and a custom model binder for the DateTime formats.

    We start by defining this view model:

    public class MyViewModel
    {
        [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
        public DateTime PreferredDate { get; set; }
    }
    

    then a controller:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var model = new MyViewModel
            {
                PreferredDate = DateTime.Now.AddDays(2)
            };
            return View(model);
        }
    
        [HttpPost]
        public ActionResult Index(MyViewModel model)
        {
            // model.PreferredDate will be correctly bound here so
            // that you don't need to twiddle with any FormCollection and 
            // removing stuff from ModelState, etc...
            return View(model);
        }
    }
    

    a View:

    @model MyViewModel
    
    @using (Html.BeginForm())
    {
        @Html.LabelFor(x => x.PreferredDate)
        @Html.EditorFor(x => x.PreferredDate)
        @Html.ValidationMessageFor(x => x.PreferredDate)
        <button type="submit">OK</button>
    }
    

    and finally a custom model binder to use the specified format:

    public class MyDateTimeModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
    
            if (!string.IsNullOrEmpty(displayFormat) && value != null)
            {
                DateTime date;
                displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
                // use the format specified in the DisplayFormat attribute to parse the date
                if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
                {
                    return date;
                }
                else
                {
                    bindingContext.ModelState.AddModelError(
                        bindingContext.ModelName,
                        string.Format("{0} is an invalid date format", value.AttemptedValue)
                    );
                }
            }
    
            return base.BindModel(controllerContext, bindingContext);
        }
    }
    

    that will be registered in Application_Start:

    ModelBinders.Binders.Add(typeof(DateTime), new MyDateTimeModelBinder());
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

So I've written this code for a sliding menu, only I'm having one problem,
I need to have only one button in showConfirmDialog . I tried this: int
I am having some trouble figuring out why I am only receiving one reply
We are having an application developed for BlackBerry - a pretty big one only.
Only one instance of a ScriptManager can be added to the page. this error
Why only one overload throws this exception? Little update: I understand that there was
I have one user (only one, all the others are fine) trying to update
I want to select only one radio button but I cant do this. Here
I found only one attempt to create such compiler - http://sourceforge.net/projects/xsltc/ . But this
I have only one class with many instances. Every instance is observer of couple

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.