ViewBag ASP NET 核心 MVC | CallSite.Target(闭包,CallSite,对象)
ViewBag ASP NET CORE MVC | CallSite.Target(Closure , CallSite , object )
我真的卡住了,我不明白这个问题。
我的意思是,我真的不明白为什么它不起作用。
这是错误:
& 这是代码,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;
[...]
}
你有什么想法吗?
查看错误,对象引用似乎有问题,可能是客户端没有数据。试图重现删除 TempData 部分并将样本数据添加到 Client 对象中的错误。它工作正常。见下文。
客户class
public class Client
{
public string Name { get; set; }
}
家庭控制器:
public IActionResult Index()
{
Client client = new Client { Name = "Rahul" };
ViewBag.client = client;
return View();
}
查看:
@{
ViewData["Title"] = ViewBag.client.Name;
}
<div class="text-center">
<h1 class="display-4">Welcome <span>@ViewBag.client.Name</span></h1>
</div>
输出
好的,现在可以了,这是我修改的内容:
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;
[...]
我真的卡住了,我不明白这个问题。 我的意思是,我真的不明白为什么它不起作用。
这是错误:
& 这是代码,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;
[...]
}
你有什么想法吗?
查看错误,对象引用似乎有问题,可能是客户端没有数据。试图重现删除 TempData 部分并将样本数据添加到 Client 对象中的错误。它工作正常。见下文。
客户class
public class Client
{
public string Name { get; set; }
}
家庭控制器:
public IActionResult Index()
{
Client client = new Client { Name = "Rahul" };
ViewBag.client = client;
return View();
}
查看:
@{
ViewData["Title"] = ViewBag.client.Name;
}
<div class="text-center">
<h1 class="display-4">Welcome <span>@ViewBag.client.Name</span></h1>
</div>
输出
好的,现在可以了,这是我修改的内容:
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;
[...]