Suppose I have c开发者_如何学JAVAodes like these
public void Upload (Picture picture)
try
{
//ps is the entity framework
ps.AddToPictures(picture);
ps.SaveChanges();
return picture.PictureId;
}
catch (Exception e) {
//some codes to bound the exception to the model
}
How can I present the exceptions to the model and present them in the view?
Use ModelState.AddError.
Example:
catch (Exception e) {
ModelState.AddError("SomeErrorKey", e.Message);
}
Then in the View:
<%= Html.ValidationMessage("SomeErrorKey") %>
Can't remember the correct overload for ValidationMessage - so take a look at the different overloads.
I'd recommend using custom exceptions though - you don't want to display things like "Null reference exception" in your View.
More on ModelState.AddError here.
精彩评论