Search code examples
asp.net-mvc-4asp.net-mvc-scaffolding

Date fields are always required in MVC Scaffolding


I have a model where i have scaffold it with Mvc Scaffolding, All Fields with DateTime Property in my model are marked as Required i mean i can not enter a null value in it. Even though in my model there is no [Required] attribute for Date fields. I want to get rid of this issue, any idea?

Here is my Model.

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

namespace MVCMembershipBootstrap.Models.FirstComponent
{
public class FirstCmActivity
{
    public int FirstCmActivityId { get; set; }
    public string Name { get; set; }
    public DateTime PlannedStartDate { get; set; }
    public DateTime PlannedEndDate { get; set; }
    public DateTime OngoingStartDate { get; set; }
    public DateTime OngoingEndDate { get; set; }
    public DateTime FinishedDate { get; set; }
    public string GizResponsible { get; set; }
    public string PartnerResponsible { get; set; }
    public string swAfghanSide { get; set; }
    public string swGiz { get; set; }
    public string swRodeco { get; set; }
    public string swExtern { get; set; }
    public string EquipmentNeeds { get; set; }
    public string EquipmentExist { get; set; }
    public string MileStone { get; set; }

    public int FirstCmOutputId { get; set; }


    public virtual FirstCmOutput Output { get; set; }
}

}

Here is My Controller...

 public class FirstCmActivitiesController : Controller
{
    private OPandMEContext context = new OPandMEContext();

    //
    // GET: /FirstCmActivities/

    public ViewResult Index()
    {
        return View(context.FirstCmActivities.ToList());
    }



    public ViewResult Report()
    {
        return View();
    }
    //
    // GET: /FirstCmActivities/Details/5

    public ViewResult Details(int id)
    {
        FirstCmActivity firstcmactivity = context.FirstCmActivities.Single(x => x.FirstCmActivityId == id);
        return View(firstcmactivity);
    }

    //
    // GET: /FirstCmActivities/Create

    public ActionResult Create()
    {
        ViewBag.PossibleFirstCmOutputs = context.FirstCmOutputs;
        return View();
    }

    //
    // POST: /FirstCmActivities/Create

    [HttpPost]
    public ActionResult Create(FirstCmActivity firstcmactivity)
    {
        if (ModelState.IsValid)
        {
            context.FirstCmActivities.Add(firstcmactivity);
            context.SaveChanges();
            Response.Redirect("http://localhost:53785/firstcmActivities/Create#services");

        }

        ViewBag.PossibleFirstCmOutputs = context.FirstCmOutputs;
        return View(firstcmactivity);
    }

Thanks


Solution

  • Just Correct your properties of Datetime as nullable.

    Example :-

     public DateTime? PlannedStartDate { get; set; }