ViewData in Asp.net Core
Packages
"Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0.2"
Controllers[Folder]
Home1Controller.cs
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ViewData.Models;
namespace ViewData.Controllers
{
public class Home1Controller : Controller
{
public IActionResult Index()
{
ViewData["var1"] = "Message comes from viewdata";
ViewData["var2"] = DateTime.Now.ToLongDateString();
//With array
string[] myarr = { "Apple", "Banana", "Grapes" };
ViewData["var3"] = myarr;
//With list
ViewData["var4"] = new List<string>()
{
"Cricket",
"Footballo",
"Hockey",
};
Student Ali = new Student();
Ali.name = "Ali Khan";
Ali.gender = "Male";
Ali.standard = 10;
ViewData["var5"] = Ali;
return View();
}
}
}
Models[Folder]
Student.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ViewData.Models
{
public class Student
{
public string name { get; set; }
public string gender { get; set; }
public int standard { get; set; }
}
}
Views[Folder]
Home1
Index.cshtml
@{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
@ViewData["var1"]
<br />
@ViewData["var2"]
@{ //TypeCasting of ViewData in String
foreach (var item in (string[])ViewData["var3"])
{
<h1>@item</h1>
}
}
@{
foreach (var item in (List<string>)ViewData["var4"])
{
<h1>@item</h1>
}
}
@{
var a = (ViewData.Models.Student)ViewData["var5"];
}
<h1>@a.name</h1>
<h1>@a.gender</h1>
<h1>@a.standard</h1>
0 Comments