How can I make an MVC POST return me to the previous page?

后端 未结 3 1088
遥遥无期
遥遥无期 2021-01-14 00:41

I have the following action which is called from a screen with a list of records.

    [HttpPost]
    //[Authorize(Roles = \"admin\")]
    public ActionResul         


        
3条回答
  •  再見小時候
    2021-01-14 01:41

    Instead of a redirection,

    [HttpGet]
    public ActionResult Index()
    {
        /// preform any processing necessary for your index page on GET
        return View("Index");
    }
    
    [HttpPost]
    public ActionResuit Edit(EditViewModel itemView)
    {
      if (ModelState.IsValid)
      {
        /// do whatever you want with your model...
      }
    
      // return the contents as they'd be rendered by the Index action
      return Index(); 
    }
    

    Note that with this method the URL in the browser will still display the Edit url (like /area_name/edit), but you can fix that by:

    1. Using a redirect (which you've said you don't want to do)
    2. Using JavaScript to update the URL, or use history.back() as @AlanStephens suggested
    3. Probably other methods that don't immediately come to mind.

    However, I'd question whether this is really the best approach. Typically, users expect different URLs to do different things.

    Or, if I understand you correctly and the edit action is being called from the Index page,

    [HttpGet]
    public ActionResult Index()
    {
      return View();
    }
    
    [HttpPost] /// from a form on Index
    public ActionResult Index(EditViewModel model)
    {
      if (ModelState.IsValid)
      {
        ////
      }
      return View();
    }
    

    and just take the /Edit out of play entirely. Again, I don't really care for this approach.

提交回复
热议问题