代码之家  ›  专栏  ›  技术社区  ›  Mike

ASP.NET MVC:返回视图时服务器验证和保留URL参数

  •  0
  • Mike  · 技术社区  · 15 年前

    我目前有以下代码可以编辑客户注释。

     [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditNote(Note note)
        {
            if (ValidateNote(note))
            {
                _customerRepository.Save(note);
                return RedirectToAction("Notes", "Customers", new { id = note.CustomerID.ToString() });
            }
            else
            {
                var _customer = _customerRepository.GetCustomer(new Customer() { CustomerID = Convert.ToInt32(note.CustomerID) });
                var _notePriorities = _customerRepository.GetNotePriorities(new Paging(), new NotePriority() { NotePriorityActive = true });
    
                IEnumerable<SelectListItem> _selectNotePriorities = from c in _notePriorities
                                                                    select new SelectListItem
                                                                    {
                                                                        Text = c.NotePriorityName,
                                                                        Value = c.NotePriorityID.ToString()
                                                                    };
    
                var viewState = new GenericViewState
                {
                    Customer = _customer,
                    SelectNotePriorities = _selectNotePriorities
                };
    
                return View(viewState);
            }
    
    
        }
    

    如果验证失败,我希望它再次呈现EditNote视图,但为类似这样的内容保留URL参数(noteid和customerid):“ http://localhost:63137/Customers/EditNote/?NoteID=7&CustomerID=28

    关于如何实现这一点有什么想法吗?

    谢谢!

    1 回复  |  直到 15 年前
        1
  •  0
  •   Dan Atkinson    15 年前

    此操作是通过使用post进行的。您不希望这些参数作为表单的一部分而不是在URL中通过吗?

    如果您需要,我想您可以对包含noteid和customerid的edit-get操作执行重定向操作。这将有效地使您的操作看起来像这样:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult EditNote(Note note)
    {
        if (ValidateNote(note))
        {
            _customerRepository.Save(note);
            return RedirectToAction("Notes", "Customers", new { id = note.CustomerID.ToString() });
        }
    
        //It's failed, so do a redirect to action. The EditNote action here would point to the original edit note url.
        return RedirectToAction("EditNote", "Customers", new { id = note.CustomerID.ToString() });
    }
    

    这样做的好处是,您已经消除了复制代码的必要性,这些代码使客户、注释和wotno无法使用。缺点(尽管我看不到它在这里的位置)是您不会返回验证失败。