Sharing Viewdata for all actions in ASP.NET MVC

On the MVC MVC application page, I have a product page (Controller: ProductController, Action: Index) that lists all the products from the database. I now have a “Add Product” link that offers a form to fill out product information. When sending from AddProduct, an action is called that calls StoredProcedure (modeled in my model class). On successful upload, I use RedirectAction ("Index"). Now my StoredProcedure returns me a message indicating the retry of the addition. I need this message to be saved in ViewData and shown on the Index page. How can i do this? Any help would be greatly appreciated.

+3
source share
1 answer

Use TempDatainstead ViewData:

public ActionResult Index() 
{
    ViewData["message"] = TempData["message"];
    return View();
}

public ActionResult AddProduct()
{
    TempData["message"] = "product created";
    return RedirectToAction("Index");
}

And in the index view:

<% if (ViewData["message"] != null) { %>
    <div><%= Html.Encode((string)ViewData["message"]) %></div>
<% } %>
+8
source

Source: https://habr.com/ru/post/1723759/


All Articles