简体   繁体   中英

How to pass data from controller to view from post method with parameter?

I have a HttpGet method with a parameter. Then I submit a form from view and action is going to the same controller with HttpPost method. In post method, I do some controls and if they fail I want to return the same view with for example a ViewBag. It's something like this:

[HttpGet]
public IActionResult someFunc(string s)
{
  ...
}

[HttpPost]
public IActionResult someFunc(int i, double d,string s)
{
  if(i < 0){
    //indicate that this is an error like ViewBag.error = "error"
    return View(s);
  }
  ...
}

In post method, I want to return the same view with indicating that there is an error. If get method was not using any parameter, it was working properly. I was doing that with a ViewBag.error = smthng but when parameters came, I couldn't figure it out. In view, in the same way I want to make that if my error type is not null show my error with an alert. I tried return Redirect(path?parameter=p) but ViewBag did not worked with that way. Same thing happened with return View(action,parameter) . How can I make it?

You can use ViewBag.Error in the post method before returning the view, the view and method have same name:

[HttpPost]
public IActionResult someFunc(int i, double d,string s)
{
   if(i < 0){
      ViewBag.Error = "Error" ;
      return View(s);
   }
}

Also, you can use Use RedirectToAction method if you want use the get method using TempData["param"] to pass the paramater in the method

[HttpGet]
public IActionResult someFunc(string s)
{
   ...
   ViewBag.Error = TempData["Error"];
   return View() ;
}

[HttpPost]
public IActionResult someFunc(int i, double d,string s)
{
   if(i < 0){
      //indicate that this is an error like ViewBag.error = "error"
      TempData["Error"] = "Error Something" ;
      string param = s ;
      return RedirectToAction("someFunc", new { s = param});
   }
   ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM