Right, so a) I'm not sure if this is the right forum for this question, I failed to find a better suggestion, and b) I couldn't find an answer to a question I can't believe I haven't asked before:
So if I have a model, standard form to fill in and it errors so I throw it back to the user, how do I, or how SHOULD I, structure the code to make sure all the supporting properties are constructed?
Example:
public ActionResult DoThing()
{
var model = new DoThingModel();
model.Things = ThingService.FetchThings();
//Do Other Things
return View(model);
}
The fairly standard GET action
[HttpPost]
public ActionResult DoThing(DoThingModel model)
{
var valid = ThingService.ValidateThing(model);
if(!valid)
{
model.ValidationMessage = "Ohh no validation failed";
model.valid = false;
return View(model); //I have't rebuilt model.Things with ThingService.FetchThings()
}
else
{
return RedirectToAction("Success");
}
}
So if the thing is valid redirect to the success page, but otherwise return the form (contained within the model) to the user with a validation message. Problem is my form page has things on it and I haven't populated the model with it.
Now, this is a very simple example and I could just pass back things in the form, or duplicate the line of code that populates it. But imagine I have a much more complicated model, with breadcrumbs, multiple properties that need populating. Code duplication = bad, so how SHOULD I be making sure the model has everything I need before passing it back? I thought about creating a service but it's a service with one function. I thought about using a constructor, but that doesn't play well with model binding. I thought about creating a DoThingModel.Init() that does all the work, but putting code like that inside a model class seems dirty. I played around with a private function in the Controller that filled in all the required properties, but this seems dirty again.
I feel like there should be a standard code pattern that goes => Create New Model => Make sure Model has everything that supports the page => return Model => validate Model => re-apply any properties => return Model => repeat until valid.
Like I said in the intro, this must be a standard thing somewhere, but I can't find it.
Aucun commentaire:
Enregistrer un commentaire