0

I'm having trouble getting validation to work on my MVC page when using Entity Framework. If someone could point out what I'm doing wrong I would appreciate it. It is definitely seeing the meta data because the labels are working. However, when I hit submit, it just continues on to the next page. Could it have something to do with the fact that I have an instance of a class inside the view model?

Meta Data Class

[MetadataType(typeof(CompanyMetaData))]
public partial class Company
{
}

[MetadataType(typeof(CompanyUserMetaData))]
public partial class CompanyUser
{
}

public class CompanyMetaData
{
    [Required(ErrorMessage = "Company Name is required")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Service Center is required")]
    public string ServiceCenterCode { get; set; }

    [Required(ErrorMessage = "Account Number is required")]
    public string AccountNumber { get; set; }

    [Required(ErrorMessage = "Edition is required")]
    public string Edition { get; set; }
}

public class CompanyUserMetaData
{
    [Required]
    [RegularExpression(@"^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$", ErrorMessage = "Invalid Email Address")]
    public string EmailAddress { get; set; }

    [Required(ErrorMessage = "Password is required")]
    public string Password { get; set; }

    [Required(ErrorMessage = "First Name is required")]
    public string FirstName { get; set; }

    [DisplayName("Last Name")]
    [Required(ErrorMessage = "Last Name is required")]
    public string LastName { get; set; }
}

View Model

public class CreateCompanyViewModel : ILayoutAwareViewModel
{
    public List<AdvisorServiceCenterVW> ServiceCenters { get; set; } 
    public LayoutViewModel LayoutViewModel { get; set; }
    public Company newCompany { get; set; }
    public CompanyUser newUser { get; set; }
    public List<FuneralHome> newFuneralHomes { get; set; }
}

Markup Sample

<div class="form-group">
    <label>@Html.LabelFor(d=>d.newUser.LastName)</label>
    <div class="controls">
        @Html.TextBoxFor(d => d.newUser.LastName, new { @class = "form-control" })
        @Html.ValidationMessageFor(d => d.newUser.LastName)
    </div>
</div>

Controller

public ActionResult CreateCompanyLocations(CreateCompanyViewModel incomingModel)
    {
        var model = (CreateCompanyViewModel)TempData["model"];

        LayoutViewModel lvm = _layoutHelper.GetLayoutViewModelData("Configure New Company");
        model.LayoutViewModel = lvm;

        model.newCompany = incomingModel.newCompany;
        model.newUser = incomingModel.newUser;

        var fhs = _siteService.GetCustomerLocations(model.newCompany.AccountNumber);
        model.newFuneralHomes = new List<FuneralHome>();
        foreach (var fh in fhs)
        {
            model.newFuneralHomes.Add(new FuneralHome()
            {
                Address = fh.Address,
                Name = fh.CustomerName,
                City = fh.City,
                AccountNumber = fh.AccountNumber,
                ServiceCenterCode = fh.ServiceCenterCode,
                State = fh.State,
                ZipCode = fh.ZipCode,
                Phone = fh.Phone,
                ContactName = fh.ContactName
            });
        }

        TempData["model"] = model;

        return View(model);
    }
1
  • Post the relevant controller code. Commented Feb 10, 2015 at 15:20

2 Answers 2

1

You need to check ModelState.IsValid in your controller code and branch accordingly. Currently your controller is just processing the model whether it is valid or not. The typical pattern looks something like this:

if(ModelState.IsValid)
{
    // Do stuff for when model is valid
}
else
{
    // return the view with the invalid model to give the user
    // a chance to fix it
    return View(model);
}
Sign up to request clarification or add additional context in comments.

4 Comments

So it doesn't work like RequiredFieldValidators in web forms? The page has to post in order for the validation to work?
There is some client-side validation that can take place, if you have that enabled, but bottom line is that if the page posts you still need to check if you've got a valid model or not.
Can I ask why this was accepted and then unaccepted?
As I stated in the answer below, this is not the answer to my question. Yes, you can do validation that way, but MVC allows you to do client side validation without ever having to go to the controller.
0

It wound up having nothing to do with the above answer. I was missing the jquery validation and jquery unobtrusive scripts on my layout page so that is what was causing the validation not to fire. You do NOT need to do anything in the controller for this to work correctly.

1 Comment

Until the minute you add a validation that can't be done client-side (e.g. a custom validator) or you encounter a client who has JavaScript turned off. When you're using data annotations you should always code your controller defensively, which means using the pattern I posted.

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.