简体   繁体   中英

How to pass model from one action to another without using TempData in ASP.NET Core MVC using C#

  public IActionResult Index(BusinessModel business)
  {
       return View(business);
  }

  public async Task<IActionResult> Insert(BusinessModel business)
  {
       var relativeUrl = "business/insert";
       var apiResponse = await PostRequest<BusinessModel, WebApiResponse<BusinessModel>>(relativeUrl, business);

       if (apiResponse.HttpStatusCode == 200)
       {
           logger.LogInformation("business detailss has been saved. ");

           business.StatusCode = 200;
           ViewBag.apiresponse = business.StatusCode;

           //return RedirectToAction("Index", "Business", BusinessResultData.Data);
           return View("Index", business);
       }
       else
       {
           logger.LogInformation("Invalid Details");

           if (apiResponse.HttpStatusCode != 400)
           {
               business.StatusCode = 500;
               return View("Index", business);
           }
           else
           {
               CheckAndAddModelStateError(apiResponse.Data.ValidationErrors);
               return RedirectToAction("Index", business);
           }
       }
   }

I wanted to send the data to index action from create page if I had some errors on server side, but when I send the data errors becomes null while using redirectToAction as I not want to use TempData .

Can you suggest any better ideas?

Thanks in advance

You can redirect using UrlHelper like this:

return Redirect(Url.Action("Index", business));

When both acttions are inside of the same controller, instead of redirection I usually call an action as a function

return Index(business);
  public Task<IActionResult> Index(BusinessModel business)
  {
       return View(business);
  }

  public async Task<IActionResult> Insert(BusinessModel business)
  {
       //Stuff
       return await Task.Run<ActionResult>(() => { return RedirectToAction("Index", business); });
  }

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