MVC setting up Html.DropdownList on ModelState.IsValid = false

前端 未结 2 1583
说谎
说谎 2021-01-22 01:17

This is something that has always puzzled me as to the best way round, while keeping maintainable code. The below code sets up a list of months and years for a payment gateway f

2条回答
  •  迷失自我
    2021-01-22 02:10

    Add a private method to your controller (the following code assumes your ExpiryMonth and ExpiryYear properties are IEnumerable which is all that the DropDownListFor() method requires)

    private void ConfigureViewModel(PayNowViewModel model)
    {
      model.ExpiryMonth = Enumerable.Range(1, 12).Select(m => new SelectListItem
      {
        Value = m.ToString(),
        Text = m.ToString("00")
      });
      model.ExpiryYear = Enumerable.Range(DateTime.Today.Year, 10).Select(y => new SelectListItem
      {
        Value = y.ToString(),
        Text = y.ToString("00")
      });
    }
    

    and then in the GET method

    public ActionResult ConfirmPayment()
    {
      PayNowViewModel model = new PayNowViewModel();
      ConfigureViewModel(model);
      return View(model);
    }
    

    and in the POST method

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult ConfirmPayment(PayNowViewModel model)
    {
      if (!ModelState.IsValid)
      {
        ConfigureViewModel(model);
        return View(model);
      }
      .... // save and redirect (should not be returning the view here)
    }
    

提交回复
热议问题