user3127986
user3127986

Reputation: 388

How can I generate an error in the TryUpdateModel() function?

I will like to test the Catch branch of a Try Catch but I don't understand how to generate an errror in the TryUpdateModel(Facture) ? I am using VS 2013 Web Express. I tried using the F10 and it goes to the Catch but no error was generated. I will like to be able to see and error in my return View page.

CheckoutController.cs

public ActionResult AddressAndPayment(FormCollection values)
{
    var facture = new Facture();
    TryUpdateModel(facture);        //I would like to generate an error here

    try
    {
        facture.DateFact = DateTime.Now; 

        //Process the order
        var cart = ShoppingCart.GetCart(this.HttpContext);
        cart.CreateOrder(facture);

        return RedirectToAction("Complete", new { id = facture.FactureId });
    }
    catch
    {
        //Invalid - redisplay with errors
        return View(facture);
    }
}

Facture.cs

 using System.Collections.Generic;
 using System.ComponentModel;
 using System.ComponentModel.DataAnnotations;
 using System.Web.Mvc;

 namespace Tp1WebStore3.Models
 {
    [Bind(Exclude = "FactureId")]

    public partial class Facture
    {
        [ScaffoldColumn(false)]
        public int FactureId { get; set; }

        [ScaffoldColumn(false)]
        public System.DateTime DateFact { get; set; }

        [Required(ErrorMessage = "Vous devez saisir votre Nom")]
        public string NomFact { get; set; }

        [Required(ErrorMessage = "Vous devez saisir votre Prenom")]
        public string PrenomFact { get; set; }

        [Required(ErrorMessage = "Vous devez saisir une adresse")]
        public string AdresseFact { get; set; }

        [Required(ErrorMessage = "Vous devez saisir une ville")]
        public string VilleFact { get; set; }

        [Required(ErrorMessage = "Vous devez saisir un code postal")]
        public string CodePostalFact { get; set; }

        [Required(ErrorMessage = "Vous devez saisir une adresse courriel")]
        [DisplayName("CourrielFact")]

        [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}",
        ErrorMessage = "Adresse courriel invalide.")]
        [DataType(DataType.EmailAddress)]
        public string CourrielFact { get; set; }

        public decimal TotalFact { get; set; }

        public List<Facture> Factures { get; set; }
    }
}

Upvotes: 0

Views: 129

Answers (1)

dav_i
dav_i

Reputation: 28107

The TryXXX pattern returns bool (true if success, false if fail)

So to test if your model update was successful you can do

if (this.TryUpdateModel(something))
{
    // success
}
else 
{
    // handle failure
}

The equivalent using Exceptions would be

try
{
    this.UpdateModel(something);
}
catch(SomeException)
{
    // handle failure
}

But throwing exceptions is expensive so this is considered bad practice especially when you have a TryXXX available.

Upvotes: 1

Related Questions