开发者

Tracking exceptions on AddObject in Entity Framework with Asp.net MVC

开发者 https://www.devze.com 2023-01-31 00:34 出处:网络
Suppose I have c开发者_如何学JAVAodes like these public void Upload (Picture picture) try { //ps is the entity framework

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号