logo
down
shadow

Problem adding string value to ViewBag from an MVC Action using TempData


Problem adding string value to ViewBag from an MVC Action using TempData

By : 지한솔
Date : November 25 2020, 07:06 PM
To fix this issue I've inherited an MVC project where the page should display a message indicating success if an invoked Action completes properly. I'm having some trouble as I am very new to MVC and web development in general.
code :
return RedirectToAction("CreateViewAction", new { @SavedMessage = savedMessage });
public ActionResult MyAction(FormCollection collection)
{
    TempData["SuccessMessage"] = @"Action completed successfully";
    //Do stuff
    return RedirectToAction("CreateViewAction");
}

public ActionResult CreateViewAction()
{
    ViewBag.SavedMessage = TempData["SuccessMessage"] ?? "Successfully!!!";
    return View();
}


Share : facebook icon twitter icon
ViewBag, ViewData and TempData

ViewBag, ViewData and TempData


By : user3722696
Date : March 29 2020, 07:55 AM
I wish this helpful for you Could any body explain, when to use ,
1)TempData
code :
public ActionResult Foo()
{
    // store something into the tempdata that will be available during a single redirect
    TempData["foo"] = "bar";

    // you should always redirect if you store something into TempData to
    // a controller action that will consume this data
    return RedirectToAction("bar");
}

public ActionResult Bar()
{
    var foo = TempData["foo"];
    ...
}
public ActionResult Foo()
{
    ViewBag.Foo = "bar";
    return View();
}
@ViewBag.Foo
public ActionResult Foo()
{
    ViewData["Foo"] = "bar";
    return View();
}
@ViewData["Foo"]
public class MyViewModel
{
    public string Foo { get; set; }
}
public Action Foo()
{
    var model = new MyViewModel { Foo = "bar" };
    return View(model);
}
@model MyViewModel
@Model.Foo
public class OneController: Controller
{
    public ActionResult Index()
    {
        TempData["foo"] = "bar";
        return RedirectToAction("index", "two");
    }
}

public class TwoController: Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            Foo = TempData["foo"] as string
        };
        return View(model);
    }
}
@model MyViewModel
@Html.DisplayFor(x => x.Foo)
public class OneController: Controller
{
    public ActionResult Index()
    {
        var id = Repository.SaveData("foo");
        return RedirectToAction("index", "two", new { id = id });
    }
}

public class TwoController: Controller
{
    public ActionResult Index(string id)
    {
        var model = new MyViewModel
        {
            Foo = Repository.GetData(id)
        };
        return View(model);
    }
}
TempData, ViewBag, nothing works

TempData, ViewBag, nothing works


By : Jay kumar
Date : March 29 2020, 07:55 AM
wish helps you In the RedirectToAction call you cause the client browser to redirect by sending it a "redirect" status. Your local state is lost as soon as you return that status and end your response - it is not persisted through to the next request. You need another "way" to persist that information, such as redirecting to SupplierEditSuccess, for example, which would be a view that assumes that the edit succeeded, or passing a Success parameter to Supplier which says that the last edit succeeded and to show a message accordingly.
However, within your exception catch, you should be able to see the TempData within the view, so if you deliberately throw an exception after this._service.Update(supplier); then you should be able to access the message in TempData["UserMessage"].
ASP.NET MVC ViewBag or TempData?

ASP.NET MVC ViewBag or TempData?


By : Luis Costa
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , I have a form in a view and I pass some information to the Controller through a Submit button. In the controller, in an ActionResult called SaveP I want to verify some conditions and to pass the result of these validations back to the view, so that it display something when the page is reloaded after pressing the submit button.
code :
RedirectToAction("P", new { id = editor.ID ,check = true});
public ActionResult P(int id,bool check=false)
{ 
  viewBag.check = check;
}
ASP.NET MVC ViewBag / TempData Security

ASP.NET MVC ViewBag / TempData Security


By : Ching Liu
Date : March 29 2020, 07:55 AM
seems to work fine TempData persists only until the next page access; ViewBag is used to pass values from the controller to the view. Neither are suitable for storing information which will last for the session. On security, they are both server side and the user will not be aware of them, so, yes, they are secure.
If you want to persists values for the duration of a session they you need a different mechanism. Several are available to you. My favourite is the use of session variables but some developers are firmly against session variables. You need to research your options further.
Problem populating the ViewBag using TempData & Redirect

Problem populating the ViewBag using TempData & Redirect


By : Khalid Shaikh
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , I needed to use a combination of TempData and the ViewBag to accomplish my goal. Here's what I did:
Worker Action Here, we just assign a string value to TempData[IDX_ACTIONRESULT] based on whether or not the action succeeds. Instead of throwing the exception, we'll log the exception and then report failure using this TempData attribute
code :
public partial class ApproveController : Controller
{
    const string IDX_ACTIONRESULT = @"ActionResult";

    public ActionResult MyAction(FormCollection collection)
     {
         try
         {
             //Do stuff
             TempData[IDX_ACTIONRESULT] = @"Action completed successfully";
             return RedirectToAction("MainWindow");
         }
         catch (Exception e)
         {
             Logger.reportException(e);
             TempData[IDX_ACTIONRESULT] = @"The Action failed. Please contact your system administrator for assistance";
         }
     }
}
public partial class ApproveController : Controller
{
    public ActionResult MainWindow()
    {   
        if (TempData[IDX_ACTIONRESULT] != null)
            ViewBag.SavedMessage = TempData[IDX_ACTIONRESULT].ToString();

        //Build the rest of the view

        return View();
    }
}
Related Posts Related Posts :
  • Stop Continuation Task upon exception thrown from parent task
  • Is there a way to make msbuild write error output to stderr?
  • Unit testing: TDD with POCO Objects with navigation properties (relationship fixup)
  • GridSplitter disables my RowDefinition style
  • Memory leak only in Release mode
  • how to read specified string from url
  • how to store html code EMail template in a string variable or textbox c#
  • Set Selected Date to TimePicker wpf (TimePickers inside DataTemplate)
  • How to draw line in Silverlight Specifying Height?
  • Stored procedure executes but does not update data
  • ASP.NET ListBox Trouble
  • Why does C# also not allow empty conditions in while loops?
  • Unable to get a block of code into my regex match groups
  • What is difference between dbcontext.Add and dbcontext.AddObject
  • How do I update the file version number of C# DLL without recompiling?
  • Value for html control always null
  • HttpClient hangs when timeout is setting (Windows Phone)
  • Handle Multiple Form tag in asp.net page?
  • create word document with html content in c#
  • Confusion about Find And Replace
  • Format sms messages in Clickatell
  • Automated Function Overload
  • String to date in MS Access SQL statement gives type mismatch error
  • ShowDialog exiting on certain events
  • Is there a try Convert.ToInt32... avoiding exceptions
  • How to move wpf application into minimize tray at Window Start-up C#?
  • How to change display format of long variable?
  • How to use Addfields in MongoDB C# Aggregation Pipeline
  • MsTest TestCleanup method not called when an unhandled exception is thrown
  • missing last data when exporting gridview to excel
  • How to add array of objects to List in c#
  • Lambda Expression to order (sort) my list collection
  • Library for displaying music notation
  • How to compare two dictionaries in c# and get the output as True and False after validation
  • specify fields to be serialized with JSON
  • How do you obtain the content of a specific node using XmlDocument in C#?
  • How to ignore the first line in a csv file when you read the csv file in C#
  • c# - Problem calling public void from class
  • How to tell a class which objects it should create? Type vs. object confusion :(
  • Save CheckBox state to xml
  • WIX CAQuietExec NETSH Command Fails
  • Issues sending http put request every 60 seconds to RoR app
  • ConfigurationManager.ConnectionStrings.ConnectionString Issue
  • Real size WPF controls for printing
  • How to cancel properly?
  • C# String multiplication error
  • Using Solrnet and Assigning Attributes with Entity Framework Generated POCOs
  • Regex pattern for single backslash
  • TextBox: insert spaces for credit card number?
  • C# DLL loaded for exe-application is not found when launching similar DLL by rundll32.exe
  • Debug a Windows Service with WCF library
  • Open a file from an external assembly?
  • Servicestack RegistrationFeature Unable to bind request
  • Index was outside the bounds of the array confusion
  • Error in Xml to List code. The ':' character, hexadecimal value 0x3A, cannot be included in a name
  • I am trying to do a while loop with a string conditional statement in C#
  • C# 'Cannot access a disposed object. Object name: 'SslStream'.'
  • How to make Gecko use seperate CookieContainer per instance?
  • C# Advanced form "please wait"
  • Send and Receive data C# using network stream
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org