实现HTTP-POST的Edit Action方法(转)

实现HTTP-POST的Edit Action方法

1.   [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(int id, FormCollection formValues) {}
表示该方法负责处理HTTP POST动作。

2.  获取表单提交的值

一个简单的办法是使用Controller基类的Request属性来访问form集合,并直接获取提交的参数值:

       public ActionResult Edit(int id, FormCollection formValues)
        {
            // Retrieve existing dinner
            Dinner dinner = dinnerRepository.GetDinner(id);
            // Update dinner with form posted values
            dinner.Title = Request.Form["Title"];
            dinner.Description = Request.Form["Description"];
            dinner.EventDate = DateTime.Parse(Request.Form["EventDate"]);
            dinner.Address = Request.Form["Address"];
            dinner.Country = Request.Form["Country"];
            dinner.ContactPhone = Request.Form["ContactPhone"];
            // Persist changes back to database
            dinnerRepository.Save();
            // Perform HTTP redirect to details page for the saved Dinner
            return RedirectToAction("Details", new { id = dinner.DinnerID });
        }

3.   使用Controller 基类的内置方法UpdateModel()。该方法支持使用传入的表单参数更新对象的属性,它使用反射机制来解析对象的属性名称,接着基于客户端传入的参数值自动赋值给对象相关属性。
    [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(int id, FormCollection formValues)
        {
            // Retrieve existing dinner
            Dinner dinner = dinnerRepository.GetDinner(id);
            UpdateModel(dinner);
            // Persist changes back to database
            dinnerRepository.Save();
            // Perform HTTP redirect to details page for the saved Dinner
            return RedirectToAction("Details", new { id = dinner.DinnerID });
        }

4.   异常处理机制说明:
  try {}
  catch
            {
                foreach (var issue in dinner.GetRuleViolations())
                {
                    ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
                }
                return View(dinner);
            }

在catch代码块中,首先遍历Dinner对象中所有规则冲突,并添加到ModelState对象中,接着重新显示视图。

posted @ 2010-07-15 14:48  Gang.Wang  阅读(968)  评论(0编辑  收藏  举报