0

is it possible to use Controller.TryUpdateModeloutside of the Controller context?

For Example suppose that I want to use Controller.TryUpdateModel method in class which does not belong to MyApp.Controllers so how that could be done?.

this is my code.

public ActionResult ValidateAndSignUp(company newCompany)
{
    if (ModelState.IsValid)
    {
        newCompany.CDTO.File = Request.Files["Logo"];
        if(new CompanyActions().AddCompany(newCompany))
        {
            ViewBag.message = newCompany.CDTO.Message;
            return View(newCompany.CDTO.RedirectTo);
        }
        else
        {
            if (newCompany.CDTO.HasFileError)
            {
                ModelState.AddModelError("Logo", "Invalid File"); 
                return View(newCompany.CDTO.RedirectTo, newCompany);
            }
            else
            {
                ViewBag.error = newCompany.CDTO.Error;
                return View(newCompany.CDTO.RedirectTo);
            }
        }
    }
    else
    {
        newCompany.CDTO.Countries = new DropDownLists().GetAllCountries();
        return View("signUp", newCompany);
    }
}
Mo Haidar
  • 3,748
  • 6
  • 37
  • 76
  • 2
    I assume your misunderstanding what `TryUpdateModel` is and does. Its purpose is to read posted form data, query string values etc, validate those values against your model properties (and its validation attributes) and add the values and any validation errors to `ModelState` (which can then be tested with `ModelState.IsValid`. None of this would make any sense outside a controller (and of course would not work because you do not have access to `FormCollection, ValueProviders, ModelState` etc) –  Aug 20 '15 at 10:47
  • @StephenMuecke I edited my question and I added my code, what I wanted is not to add the file error in the controller method, instead of that I wanted to do that in the model class – Mo Haidar Aug 20 '15 at 12:38
  • Sorry, not sure what you are really trying to achieve. Of course you can do your own validation in the class (usually by having your class implementing `IValidatableObject` - refer an example [here](http://stackoverflow.com/questions/3400542/how-do-i-use-ivalidatableobject)), but that has nothing to do with `TryUpdateModel` which will only work in the controller. –  Aug 20 '15 at 12:46

0 Answers0