-1

I'm actually stuck & I don't understand this issue. I mean, I really don't get it why it doesn't work.

Here's the error : error

& here's the code, Index.cshtml :

@{
    ViewBag.Title = ViewBag.client.Name;
}
[...]

HomeController.cs :

private readonly CoreDataBase dataBase = new CoreDataBase();
public ActionResult Index()
{
    Client client;

    if (TempData["client"] != null) {
        client = (Client)TempData["client"];
    }
    else {
        client = dataBase.getClient(company);
        TempData["client"] = client;
    }

    ViewBag.client = client;
    [...]
}

Do you have any idea?

Hashka
  • 395
  • 3
  • 10
  • Try casting the object. – Rahul Jha Dec 16 '20 at 11:46
  • @RahulJha hi, wich object & how ? – Hashka Dec 16 '20 at 11:48
  • please check if your db object is correct. It is throwing null reference error which means there is a problem with client which get data from tempdata/db. No problem with ViewBag.client.Name. Check my sample below. – Rahul Jha Dec 16 '20 at 11:56
  • Did you use asp.net mvc instead of asp.net core mvc?In asp.net core mvc it works well although the value is null. – Rena Dec 17 '20 at 02:31

2 Answers2

0

Looking at error, it seems issue with object reference, might possible that Client has no data. Tried to reproduce error removing TempData part and adding sample data into Client object. It is working fine. See below.

Client class

public class Client
    {
        public string Name { get; set; }
    }

HomeController:

public IActionResult Index()
        {
            Client client = new Client { Name = "Rahul" };

            ViewBag.client = client;
            return View();
        }

View:

@{
    ViewData["Title"] = ViewBag.client.Name;

}

<div class="text-center">
    <h1 class="display-4">Welcome <span>@ViewBag.client.Name</span></h1>
    
</div>

Output

enter image description here

Rahul Jha
  • 874
  • 1
  • 11
  • 28
0

Ok, now it works, here's what I've modified :

Client client;

if (HttpContext.Session.GetString("client") != null) 
{
  client = JsonConvert.DeserializeObject<Client>(HttpContext.Session.GetString("client"));
}
else 
{
  client = dataBase.GetClient(company);
  HttpContext.Session.SetString("client", JsonConvert.SerializeObject(client));
}

ViewBag.client = client;
[...]
Hashka
  • 395
  • 3
  • 10