Subby
Subby

Reputation: 5480

ASP.NET MVC Validation on Complex Model

I am having difficulty in validation a Form on a View.

I have a controller that does a UpdateModel(object); and therefore not sure how to build validation.

I have added [Required(ErrorMessage = "Please enter a contact name")] for all properties that are mandatory.

How do I make it all work? Since my Controller is doing some complex stuff. Below is the Controller code:

        [HttpPost]
    public ActionResult PersistListing()
    {
        var listingView = new MaintainListingView();

        if (!string.IsNullOrEmpty(Request["Listing.Guid"]))
        {
            var dbListing = _service.GetByGuid<Listing>(Guid.Parse(Request["Listing.Guid"]));

            if (dbListing != null)
            {
                listingView.Listing = dbListing;
            }
        }

        UpdateModel(listingView);    
        RebindTranslationsDictionary(listingView.Listing);
        listingView.Listing.CategoryId = _service.GetByGuid<ListingCategory>(listingView.SelectedListingCategoryGuid).Id;
        _service.PersistEntity(listingView.Listing);
        return RedirectToAction("Edit", new { id = listingView.Listing.Guid });

    }

When I uncomment the Required attributes on the base Model then I get an error when I try to to UpdateModel();

Can anyone see a quick fix to this?

EDIT: I am using I am using Html.TextBoxFor() to create controls on the View.

Added TryUpdateModel but unsure how to redirect the user with populated error messages:

     if (TryUpdateModel(listingView))
        {

            RebindTranslationsDictionary(listingView.Listing);

            listingView.Listing.CategoryId =
                _service.GetByGuid<ListingCategory>(listingView.SelectedListingCategoryGuid).Id;


            _service.PersistEntity(listingView.Listing); //save the ting


            return RedirectToAction("Edit", new {id = listingView.Listing.Guid});
          }

Do I need an EditForModel tag in my View?

Upvotes: 0

Views: 148

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039468

You could use TryUpdateModel instead of UpdateModel as it will not throw exceptions and allow you to know whether validation has failed or not:

if (!TryUpdateModel(listingView))
{
    // there were validation errors => redisplay the view 
    // so that the user can fix those errors
    return View(listingView);
}  

// at this stage you know that validation has passed 
// and you could process the model ...

Upvotes: 1

Related Questions