Lars Holdgaard
Lars Holdgaard

Reputation: 9966

Invalid modelstate: how to return to view when I have dropdownlists?

I have a big view with more than 40 fields. Some of these fields are dropdownlists, that I populate with a list of selectlistitems.

I am using the annotations on my viewmodel, to make some of them required.

Now I want to make the ModelState.IsValid check, and return to the original view with errors if there is some errors.

Problem is, if I simply make a return View(model), all my dropdownlists will crash the site, as they need to be populated again to load the page.

So my question is: how do i handle the return when modelstate is invalid.

My controller:

    public ActionResult CreateSelling(SellingAdViewModel model)
    {
        if (ModelState.IsValid)
        {
            SellingAdvert sellingAdvert = setSellingAd(model);

            var stored_advert = sellingAdvertService.Create(sellingAdvert);



            if (User != null && User.Identity.IsAuthenticated)
            {
                if (model.AcceptPartner)
                {
                    notifyPartner(stored_advert);
                }

                return RedirectToAction("Upgrade", "Ads", new { AdvertID = stored_advert.Id });
            }
            else
            {
                return RedirectToAction("ActivateAnonymous", "Ads", new { AdvertID = stored_advert.Id, anonymousId = model.UserId, AdvertType = "selling" });
            }
        }

        return View(model);
    }

My viewmodel (I have a SellingAdViewModel that derives from this one and add more properties):

public class BasicAdViewModel
{
    public int SectorId { get; set; }
    public Guid UserId { get; set; }
    public bool IsAnonymousUser { get; set; }
    public int AdvertId { get; set; }

    [DisplayName("Titel:")]
    [Required(ErrorMessage = "Titel skal udfyldes")]

    public string Headline { get; set; }

    [DisplayName("Beskrivelse:")]
    [StringLength(50, ErrorMessage = "Beskrivelsen minimum fylde 50 karakterer")]
    public string Description { get; set; }

    [DisplayName("Søgeord:")]
    public string SearchWords { get; set; }


    [DisplayName("Undertitel:")]
    public string Subtitle { get; set; }

    [DisplayName("Type af drift")]
    public List<SelectListItem> OperationTypes { get; set; }

    [Required]
    public int SelectedOperationTypeId { get; set; }


    [Required]
    public int SelectedSectorId { get; set; }
    public IEnumerable<GroupedSelectListItem> Sectors { get; set; }
}

Setting my dropdownlists in the first place:

My model has the List<SelectListItem> properties, and I fill them by having a couple of helper methods:

  SellingAdViewModel model = new SellingAdViewModel()
            {
                BusinessEntityTypes = ModelListHelpers.GetBusinessEntityTypes(),
                FoundedYears = ModelListHelpers.GetFoundedYears(null),
                ReasonForSale = ModelListHelpers.GetReasonForSale(),
                RevenuePrediction = ModelListHelpers.GetRevenuePrediction(),
                RevenueStatus = ModelListHelpers.GetRevenueStatus(),
                OperationTypes = ModelListHelpers.GetOperationTypes(),
                Region = ModelListHelpers.GetRegions(),
                Turnover = ModelListHelpers.Turnovers(),
                OperatingIn = ModelListHelpers.OperatingIn(),
                AmountOfEmployees = ModelListHelpers.GetAmountOfEmployees()
            };

Upvotes: 1

Views: 928

Answers (1)

theLaw
theLaw

Reputation: 1291

I suggest you this solution put your model in a TempData during your GET action And if the model state is invalid you make an assignment like this

public ActionResult CreateSelling(SellingAdViewModel model)
{
    if (ModelState.IsValid)
    {
        SellingAdvert sellingAdvert = setSellingAd(model);

        var stored_advert = sellingAdvertService.Create(sellingAdvert);



        if (User != null && User.Identity.IsAuthenticated)
        {
            if (model.AcceptPartner)
            {
                notifyPartner(stored_advert);
            }

            return RedirectToAction("Upgrade", "Ads", new { AdvertID = stored_advert.Id });
        }
        else
        {
            return RedirectToAction("ActivateAnonymous", "Ads", new { AdvertID = stored_advert.Id, anonymousId = model.UserId, AdvertType = "selling" });
        }
    }

    model.YourList = TempData.Peek("YourList");
    return View(model);
}

Upvotes: 3

Related Questions