一、从Controller中返回json数据
我们修改一下Index方法中的返回值
public IActionResult Index(int id,string name)
{
var stu = new Student { Name = name, ID = id };
return Json(stu);
}
二、从Controller中返回内容协商内容
public IActionResult Index(int id,string name)
{
var stu = new Student { Name = name, ID = id };
return new ObjectResult(stu);
}
上面的示例代码遵循内容协商,但是为了让代码能够返回XML格式的数据,我们还需要调用ConfigureServices()方法中的AddXmlSerialzerFormatters()。
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews().AddXmlSerializerFormatters();
}
这样,如果将请求头设置为application/xml,则返回XML数据。如果将请求头设置为application/json,则返回JSON数据。(怎么设置呢?暂时还不知道)
三、从Controller中返回View
现在我们在HomeController中添加一个方法
public IActionResult Test()
{
return View();
}
然后通过url映射到该方法会发现出错:
View() 方法是由基类Controller提供,默认情况下,会去查找具有与方法名称相同的.cshtml的视图文件。首先在/Views/Home/文件夹中查找,然后在/Views/Shared/文件夹中查找。
当然,也可以自己指定视图:
public IActionResult Test()
{
return View("Test1");
}
四、从Controller传递数据到View
在ASP.NET Core mvc中,有以下三种方法可以将数据从Controller传递到view
- 使用ViewData
- 使用ViewBag
- 使用强类型模型对象,也叫做强类型视图
4.1 使用ViewData传递数据给View
ViewData是一个弱类型的字典对象,使用string类型的键值对来存储和查询字典中的数据,如果访问的是其他类型的数据,则我们需要将其显示的转换为我们期望的类型。
public IActionResult Test()
{
var stu = new Student { Name = "Bobo", ID = 999 };
ViewData["PageTitle"] = "Test.....";
ViewData["model"] = stu;
return View();
}
@using mvc.Models
<h1>@ViewData["PageTitle"]</h1>
@{var stu = ViewData["model"] as Student; }
<div>
Name:@stu.Name
</div>
<div>
ID:@stu.ID
</div>
4.2 使用ViewBag传递数据给View
ViewBag中使用的是动态属性而不是字符串键值对,在view中访问ViewBag,需要使用相同的动态属性来访问ViewBag数据。
public IActionResult Test()
{
var stu = new Student { Name = "Bobo", ID = 999 };
//使用动态属性
ViewBag.PageTitle = "Test......";
ViewBag.model = stu;
return View();
}
<h1>@ViewBag.PageTitle</h1>
<div>
Name:@ViewBag.model.Name
</div>
<div>
ID:@ViewBag.model.ID
</div>
4.3 强类型视图
将数据从控制器传递到视图的首选方法是使用强类型视图。要创建强类型视图,只需要将模型对象传递给View()方法。
public IActionResult Test()
{
var stu = new Student { Name = "Bobo", ID = 999 };
//使用动态属性
ViewBag.PageTitle = "Test......";
//ViewBag.model = stu;
return View(stu);
}
在view层中,需要使用@model指令指定模型类型,注意指定类型的时候是小写model。然后要访问模型对象属性的时候,需要使用大写@Model。
@model mvc.Models.Student
<h1>@ViewBag.PageTitle</h1>
<div>
Name:@Model.Name
</div>
<div>
ID:@Model.ID
</div>
性的时候,需要使用大写@Model。
@model mvc.Models.Student
<h1>@ViewBag.PageTitle</h1>
<div>
Name:@Model.Name
</div>
<div>
ID:@Model.ID
</div>
强类型视图与ViewData、ViewBag不同,强类型视图提供编译时类型检查与只能提示。建议使用强类型视图将数据从控制器传递到视图。