ValidationSummary method showing validation error on initial load

喜欢而已 提交于 2019-12-14 03:19:41

问题


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);
    }

回答1:


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); 
  }


来源:https://stackoverflow.com/questions/24833360/validationsummary-method-showing-validation-error-on-initial-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!