我在文章,书籍和例子中看到过许多创建动作的例子.似乎有两种流行的风格.
[AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(FormCollection collection) { try { var contact = Contact.Create(); UpdateModel<Contact>(contact); contact.Save(); return RedirectToAction("Index"); } catch (InvalidOperationException ex) { return View(); } }
和…
[AcceptVerbs(HttpVerbs.Post)] public ActionResult Create([Bind(Exclude="Id")]Contact contact) { try { contact.Save(); // ... assumes model does validation return RedirectToAction("Index"); } catch (Exception ex) { // ... have to handle model exceptions and populate ModelState errors // ... either here or in the model's validation return View(); } }
我已经尝试了两种方法,并且都有优点和缺点,IMO.
例如,当使用FormCollection版本时,我必须在我的模型绑定器中手动处理“Id”,因为绑定/排除在此处不起作用.使用方法的类型化版本,我根本不能使用模型绑定器.我喜欢使用模型绑定器,因为它允许我填充ModelState错误,而不需要在模型的验证代码中了解ModelState.
任何见解?
更新:
我回答了我自己的问题,但是如果有人有更好的答案,我不会将其标记为几天.
解决方法
如果要更新已存在的模型对象,可以使用UpdateModel,您可以从数据库获取该模型对象,或者希望以某种特定方式实例化模型对象
例如:
[AcceptVerbs(HttpVerbs.Post)] public ActionResult EditEmployee(int id,FormCollection collection) { try { Contact contact = repository.getContact(id); UpdateModel(contact,collection.TovalueProvider()); repository.save(); return RedirectToAction("Index"); } catch { //Handle return View(); } }
如果您没有上述要求,请将其作为操作参数.
原文地址:https://www.jb51.cc/aspnet/247266.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。