views:

33

answers:

1

Hi. I wonder if there is a way to validate just one of my models in the viewmodel send it to my action? I use the DataAnnotations as validate rules.

Like the if (!ModelState.IsValid)

let me know if the question is unclear and I will edit for a better explination

EDIT my viewmodel looks like this

public class CompaniesViewModel
{
    public Core.Model.Customer Company { get; set; }        
    public IEnumerable<SelectListItem> Items { get; set; }        
    public Core.Model.Meeting Meeting { get; set; }
}

What I want to do in this particular situation is to validate just Customer. I cant do the ModelState.IsValid then all get validated. So how can I do to just validate one of them like customer in this case. Hope this was more clear

A: 

There are a number of different ways you can do this. The first is to add a property called IsValid that checks the property. So something like:

public class Company
{
  public bool IsValid
  {
    get { return GetValid() }
  }

  private bool IsValid()
  {
    if ( Some check here )
      return false;
  }
}


[HttpPost]
public ActionResult SomeAction(CompaniesViewModel model)
{
  if (model.Company.IsValid)
  {
  }
}

However a better solution IMO would be just to post the Company to your controller rather than your entire view model. Just because your passing a view model to a view it doesn't mean that you need to post the entire view model back. When you create your HTML form specify only the properties you want to post back to your controller. So for example your controller would become:

[HttpPost]
public ActionResult SomeAction(Company company)
{
  if (Model.IsValid)
  {
  }
}

Now when you check if Model.IsValid it just check company as that is all you've passed back to the controller.

Simon G