4
\$\begingroup\$

I'm putting together a basic web app in .NET core 2.1 MVC to try and better understand how it works. Currently I'm working on returning validation to the UI. Once I have this working I then want to use the same service class for a Web API front end too.

Currently the Create Action in the Controller calls the service layer, which returns my ValidationResultModel. This is then checked and errors are displayed or redirected to the index if all was ok.

[HttpPost]
[ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(CreateSupplierViewModel createSupplierViewModel)
    {          
        if (ModelState.IsValid)
        {               
            Suppliers suppliers = _mapper.Map<Suppliers>(createSupplierViewModel);
            SuppliersService suppliersService = new SuppliersService(_context);
            ValidationResultModel returnData = suppliersService.Add(suppliers);
            if(returnData.Message== "Success")
            {
                return RedirectToAction(nameof(Index));
            }

            foreach (ValidationError ve in returnData.Errors)
            {
                ModelState.AddModelError(ve.Field, ve.Message);
            }           
        }
        return View(createSupplierViewModel);
    }

In the supplierService Add Method I check if the accounts ID has been used, and run some other fluentvalidaion in the SupplierValidator class

public ValidationResultModel Add(Suppliers newSupplier)
    {
        ValidationResultModel vrm = new ValidationResultModel();

        var suppliers = _stockContext.Suppliers.Where(supplier => supplier.AccountsId == newSupplier.AccountsId).FirstOrDefault();
        if (suppliers != null)
        {
            vrm.Message = "Failure";
            ValidationError re = new ValidationError("AccountsId", "This Accounts ID already exists");
            vrm.Errors.Add(re);
        }

        SupplierValidator supplierValidator = new SupplierValidator();
        var results = supplierValidator.Validate(newSupplier);
        if (!results.IsValid)
        {
            foreach (var validationError in results.Errors)
            {
                vrm.Message = "Failure";
                vrm.Errors.Add(new ValidationError(validationError.PropertyName, validationError.ErrorMessage));
            }
        }

        if (vrm.Message != "Failure")
        { 
        _stockContext.Add(newSupplier);
        _stockContext.SaveChanges();
    }

        return vrm;
    }

Validation Classes:

public class ValidationError
{

    public string Field { get; }

    public string Message { get; }

    public ValidationError(string field, string message)
    {
        Field = field != string.Empty ? field : null;
        Message = message;
    }
}

public class ValidationResultModel
{
    public string Message { get; set; }

    public List<ValidationError> Errors { get; set; }

    public ValidationResultModel()
    {
        Message = "Success";
        Errors = new List<ValidationError>();
    }
}

Everything is functioning, but it feels very clunky. One of my main worries is what happens when I want to send back something in addition to the ValidationResultModel. Is there a better way of doing this. Or indeed a set of Core classes that do exactly this, that I need to read up on?

\$\endgroup\$
  • \$\begingroup\$ What .Net Core version do you use? \$\endgroup\$ – Adrian Iftode Mar 19 at 19:12
  • \$\begingroup\$ Using .Net Core 2.1. The Code is working fine, but I'm not sure about the best way to deal with the possible exceptions that could be generated. \$\endgroup\$ – jimmy Mar 20 at 9:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.