Search code examples
c#validationasp.net-mvc-4validationsummary

ValidationSummary method showing validation error on initial load


When using ValidationSummary(), I am seeing a required error for Name on initial create.

I've tried both initializing Name="" in the constructor and not initializing (comes through as Name=null) - same result.

How can I get the ValidationSummary() to not display the initial error on this field?

Model

public class Scenario
{
    public Int32 ID { get; set; }
    //user input
    [Required]
    [DisplayName("Scenario Name")]
    public String Name { get; set; }
    [Required]
    [DisplayName("Location")]
    public Int32 LocationId { get; set; }
    //..lots more, but omitted for question length

Controller

    // GET: Scenario/Create
    public ActionResult Create(Scenario copyFrom = null)
    {
        var vm = new EditScenarioViewModel
        {
            scenario = copyFrom ?? new Scenario(User.Identity.Name),
        };
        var periods = _performancePeriods.GetPeformancePeriodsHistory().ToList();
        vm.scenario.FiscalPeriodStarting = periods.ElementAt(2).PerformancePeriodID; //default is 3rd period back
        vm.scenario.FiscalPeriodEnding = periods.ElementAt(0).PerformancePeriodID;
        vm = PrepareDropdowns(vm);
        return View(vm);
    }

Solution

  • Instead of passing the parameter use TempData:

    copyMe.ID = 0; //reset ID 
    TempData["CreateCopy"] = copyMe 
    return RedirectToAction("Create"); 
    

    Create() with no parameters:

    public ActionResult Create() 
    { 
      scenario = TempData["CreateCopy"] as Scenario; 
      if (scenario == null) 
      { 
        scenario = new Scenario(User.Identity.Name); 
      }