Example #1
0
        public IHttpActionResult PostWorker(Worker worker)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Workers.Add(worker);
            db.SaveChanges();
            //补充代码,实现输入错误则弹出提示消息
            //try
            //{
            db.SaveChanges(); //模型验证不通过Will throw validation exception
            //}
            //catch
            //  {
            //    ViewBag.message="输入信息有误";
            //  }

            return CreatedAtRoute("DefaultApi", new { id = worker.Id }, worker);
        }
Example #2
0
        public IHttpActionResult PutWorker(int id, Worker worker)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != worker.Id)
            {
                return BadRequest();
            }

            db.Entry(worker).State = EntityState.Modified;

            try
            {
                db.SaveChanges();//用于将实体的改变保存到数据库
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!WorkerExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;//throw[表达式],不带表达式的throw语句只能用在catch语句块中
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }