Пример #1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            DBContext = new PostDbContext();

            if (Page.IsPostBack)
            {
                PostValidator validator = new PostValidator();
                Post          entity    = new Post()
                {
                    // Map form fields to entity properties
                    Id    = Convert.ToInt32(PostId.Value),
                    Title = PostTitle.Text.Trim(),
                    Body  = PostBody.Text.Trim()
                };
                ValidationResult results = validator.Validate(entity);

                if (results.IsValid)
                {
                    // Save to the database and continue to the next page
                    DBContext.Posts.Add(entity);
                    DBContext.SaveChanges();
                }
                else
                {
                    BulletedList summary = (BulletedList)FindControl("ErrorSummary");

                    // Display errors to the user
                    foreach (var failure in results.Errors)
                    {
                        Label errorMessage = FindControl(failure.PropertyName + "Error") as Label;

                        if (errorMessage == null)
                        {
                            summary.Items.Add(new ListItem(failure.ErrorMessage));
                        }
                        else
                        {
                            errorMessage.Text = failure.ErrorMessage;
                        }
                    }
                }
            }
            else
            {
                // Display form
                Post entity = DBContext.Posts.SingleOrDefault(p => p.Id == Convert.ToInt32(Request.QueryString["id"]));
                PostBody.Text  = entity.Body;
                PostTitle.Text = entity.Title;
            }
        }
Пример #2
0
 public void SavePost(Post post)
 {
     _dbContext.Posts.Add(post);
     _dbContext.SaveChanges();
 }