0

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?

1
  • 1
    Can you show us your model? And what is the exact error you're getting? Commented Sep 20, 2012 at 11:34

1 Answer 1

1

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 ...
Sign up to request clarification or add additional context in comments.

10 Comments

But I want the error messages to show. I am using Html.TextBoxFor() to create the controls.
Then add a corresponding Html.ValidationMessageFor(x => x.SomeProperty) helper. Or use Html.ValidationSummary() to display all error messages.
Ok... Because my View is strongly typed, and if the TryUpdateModel fails, how do I redirect the user to the same view with the Error messages turned ON?
You simply return the view and pass the view model to it: return View(listingView);. There's no such thing in ASP.NET MVC as Error messages turned ON. If you have placed ValidationMessageFor helpers inside this view and there are errors in the ModelState then these errors will be shown. And it is the TryUpdateModel method that is adding those error messages to the ModelState when performing the model binding from the request values.
I have added the ValidationMessageFor on a Telephone input control but it doesn't error messages don't show: @Html.ValidationMessageFor(m => m.Listing.TelephoneNumber) @Html.TextBoxFor(m => m.Listing.TelephoneNumber)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.