ttmind

Main Navigation

ttmind
  • jim-jams
  • Tech
  • Positive
Login

Login

Facebook Google

OR

Remember me Forgot password?

Don't have account? Signup here.

Sort by Categorys

.Net

PHP

Java

JavaScript

Database

Server

Client Side

Tools

Artificial Intelligence

Cloud

Hybrid Development

Event

Smart City

Education

Security

Scrum

Digital Marketing

APP Development

Business

Internet

Simulation

Art

Network

Microservices

Architecture

Technology

Leadership

    Top Articles

  • How Does Social Media Bring People Together?
    TTMind Author
  • How to read appSettings JSON from Class Library in ASP.NET Core
    Anil Shrestha
  • Printing Support In Asp.Net Core
    TTMind Author
  • HOW TO EXTRACT TEXT FROM IMAGE USING JAVASCRIPT (OCR with Tesseract.js)?
    Prakash Pokhrel
  • Images Upload REST API using ASP.NET Core
    Prakash Pokhrel
  • Related Topic

  • How to read appSettings JSON from Class Library in ASP.NET Core
  • Printing Support In Asp.Net Core
  • Images Upload REST API using ASP.NET Core
  • How to use IActionFilter, IAsyncActionFilter in ASP.NET Core MVC?
  • ASP.NET CORE - Blazor CRUD operation using ADO.NET
  • Tech
  • About Us
  • Contact Us
  • TechHelp
  • PositiveHelp
  • Jim-Jams Help
  • Terms & Conditions

© Copyright ttmind.com

Main Content

What is TempData? How to store object in TempData?

.Net .Net Core about 7 years ago || 11/4/2018 || 3.3 K View

  • Hide

Temp Data

It is used to store temporary data. TempData keeps the records  for the time of an HTTP Request. It works as a container.

It  maintains data when we move from one controller to other controller or from one action to another action. when we redirect the  it helps to maintain data between those redirects. It  uses the session variables. It is used to transfer data from one action method to another action function to the same or different controllers. TempData is stored in the Session variable.

TempData cannot be used to store complex object.

But How can we  Store Object in TempData?

 TempData can be used to store the object  by converting object into String 

Example of TempData with full code

Here is the simple form with two field for student First Name and Last Name.

Create a   Model as shown below:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace WebApp.Models
{
    public class StudentModel
    {
        [Required (ErrorMessage ="please enter your first name")]
        public string FirstName { get; set; }
        [Required (ErrorMessage ="please enter your last name")]
        
        public string LastName { get; set; }
    }
}

 

In startup we have to add

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace WebApp
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc()
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                .AddSessionStateTempDataProvider();//Add this line
            services.AddSession();//Add this line

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseSession();//Add this line for session

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

 

Full Code in the Controller is:  I have used Homecontroller

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using WebApp.Models;

namespace WebApp.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public IActionResult StudentForm()
        {
            ViewBag.IsValid = false;
            StudentModel objstudent = new StudentModel();
    

            return View(objstudent);
        }
        [HttpPost]
        public IActionResult StudentForm(StudentModel student1)
        {
            ViewBag.IsValid = false;
            StudentModel std = new StudentModel();
            if (ModelState.IsValid)
            {
                
                ViewBag.IsValid = true;
                string mystringobj = JsonConvert.SerializeObject(student1);
//object is converted into string
                TempData["Mydata"] = mystringobj;
                return View(student1);
            }
            else
            {
                ModelState.AddModelError("Invalid", "Hello i got error");
                return View(student1);
            }

        }
        [HttpGet]
        public IActionResult StudentShow()
        {
            StudentModel objstudent = new StudentModel();
            if (TempData["Mydata"] != null)
            {
                objstudent =  JsonConvert.DeserializeObject<StudentModel>(TempData["Mydata"] as string);//convert string to object
                return View(objstudent);
            }
            return View(objstudent);
        }

    }
}

 

The two view created here is StudentForm and StudentShow.

StudentForm is for taking input from the user.

Code in student form is:

@model StudentModel;
@{
    ViewData["Title"] = "StudentForm";
}
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
}

<h2>Enter your Details</h2>
@if (ViewBag.IsValid)
{
    <a href="/Home/StudentShow">See Your details.</a>
}
<form action="/Home/StudentForm" method="post" >
    

    <div class="form-group">
        <label asp-for="FirstName"></label>
        <input asp-for="FirstName" class="form-control" />
        <span class="text-danger" asp-validation-for="FirstName"></span>
        </div>
    <div class="form-group">
            <label asp-for="LastName"></label>
            <input asp-for="LastName" class="form-control" />
            <span class="text-danger" asp-validation-for="LastName"></span>
            <input type="submit" class="btn btn-primary" name="submit" />
        </div>
</form>

 

Output  form is shown below:

 

Code in the SudentShow form is:

@model StudentModel;
@{
    ViewData["Title"] = "StudentForm";

}
<h2>Show Details</h2>
<form action="StudentForm" method="post" >

    <div class="form-group">
        <label asp-for="FirstName">First Name</label>
        <p>@Model.FirstName</p>
        </div>
    <div class="form-group">
        <label asp-for="LastName">Last Name</label>
        <p>@Model.LastName</p>
    </div>
        </form>

 

The output shown below  is the final output after using the TempData. It is very useful while filling the form, If the validation is applied in the form and after clicking on the submit button  if the user leaves the  field empty then a warning message will be displayed below the empty field .The TempData will store the validated field and user have to fill the empty field. 

 

After filling the form completely and validating field, it will show the output as shown below.

 

  • 1
  • 0
  • 0
    • Facebook
    • Twitter
    • Google +
    • LinkedIn

About author

Manish Pandit

Manish Pandit

Reset Your Password
Enter your email address that you used to register. We'll send you an email with your username and a link to reset your password.

Quick Survey