As stated in the title: how does razor know when the page should be rendered in error or normal state?
I need to know this information so I can display a page in error mode with validation messages displayed etc. Unfortunately I cannot simply do View() because the code which finds the model in invalid state is in subview.
EDIT
I’m trying to do something like this to force razor to render a view in error mode:
// just for tests....
// model: a model which was marked as invalid in different controller
// state: state of the model from that controller
public ActionResult asdf(TModel model, ModelStateDictionary state) {
var result = View(this.Partial, model);
result.ViewData.ModelState.Clear();
foreach (var x in state) {
result.ViewData.ModelState.Add(x.Key, x.Value);
}
return result;
}
EDIT2
Final solution. In the previous attempt auto-deserialization from Json to c# types didn’t work (sic!) so I’ve decided to receive a plain json string and deserialize it with another library like so:
public ActionResult ErrorIndex(string jsonParamsString) {
var param = Newtonsoft.Json.JsonConvert.DeserializeObject<ForceInvalidStateRequestArg<TModel>>(jsonParamsString);
if (param != null && param.Errors != null) {
this.ModelState.Clear();
foreach (var s in param.Errors) {
this.ModelState.AddModelError(s.PropertyName, s.ErrorMessage);
}
}
var result = View(this.PartialName, param == null ? this.NewModel : param.Model);
return result;
}
Information about model validity is stored in
ModelStateobject.Which is accessible in controller like:
In view:
To your EDIT:
You can add model validation errors like this:
So if you want to force @razor to render validation error messages. It could look like: