闽公网安备 35020302035485号
public IActionResult NameofAction()
{
return View();
}
这个方法返回一个IActionResult并且方法的名称为NameofAction, action 方法的返回类型可以是像C#函数中的任何类型,IActionResult,ActionResult,JsonResult,string,StatusCodeResult是常用的类型,IActionResult VS ActionResult - IActionResult 是一个接口 ,ActionResult是一个抽象类继承自IActionResult接口,在WebAPI中你将使用ActionResult返回客户端响应。using AspNetCore.Action.Models;
using Microsoft.AspNetCore.Mvc;
namespace AspNetCore.Action.Controllers
{
public class EmployeeController : Controller
{
// 堆代码 duidaima.com
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(int id, string name)
{
string welcomeMessage = $"Welcome Employee: {name} with id: {id}";
return View((object)welcomeMessage);
}
}
}
Action方法返回IActionResult类型,调用View()方法返回一个字符串到View,注意我们如果将string类型传递到View,需要将它转换成object类型- View((object)string)。在Views->Employee文件夹下添加Index.cshtml视图,Index试图的代码如下:@model string;
<h2>填充并且提交表单</h2>
@{
if (Model != null)
{
<h3 class="p-3 mb-2 bg-success text-white">@Model</h3>
}
}
<form class="form-horizontal" method="post">
<div class="mb-3 row">
<label class="col-sm-1 control-label">编号</label>
<div class="col-sm-11">
<input class="form-control" name="id" />
</div>
</div>
<div class="mb-3 row">
<label class="col-sm-1 control-label">姓名</label>
<div class="col-sm-11">
<input class="form-control" name="name" />
</div>
</div>
<div class="mb-3 row">
<div class="col-sm-11 offset-sm-1">
<button type="submit" class="btn btn-primary">提交</button>
</div>
</div>
</form>
这里有几个值得注意的点:
namespace AspNetCore.Action.Models
{
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public int Salary { get; set; }
public string Designation { get; set; }
public string Address { get; set; }
}
}
现在将类返回给视图,在EmployeeController中添加一个新的action方法Detail[HttpGet]
public IActionResult Detail()
{
return View();
}
[HttpPost]
public IActionResult Detail(int id, string name)
{
var employee=new Employee();
employee.Id = id;
employee.Name = name;
employee.Salary = 1000;
employee.Designation = "Manager";
employee.Address = "New York";
return View(employee);
}
HttpGet 版本的 Detail方法不会向视图返回任何内容,HttpPost版本的Detail方法中给客户返回一个Employee对象,最后我们将该对象返回给视图。接下来在Views->Employee文件夹中创建Detail.cshtml的Razor视图,注意这次我们在视图的顶端定义了一个Employee类型-@model Employee。@model Employee;
<h2>填充并且提交表单</h2>
@{
if (Model != null)
{
<h3 class="p-3 mb-2 bg-success text-white">
员工详细信息:@Model.Id,@Model.Name,@Model.Salary,@Model.Designation,@Model.Address
</h3>
}
}
<form class="form-horizontal" method="post">
<div class="mb-3 row">
<label class="col-sm-1 control-label">编号</label>
<div class="col-sm-11">
<input class="form-control" name="id" />
</div>
</div>
<div class="mb-3 row">
<label class="col-sm-1 control-label">姓名</label>
<div class="col-sm-11">
<input class="form-control" name="name" />
</div>
</div>
<div class="mb-3 row">
<div class="col-sm-11 offset-sm-1">
<button type="submit" class="btn btn-primary">提交</button>
</div>
</div>
</form>
接下来我们将Employee对象的值显示在页面上,运行应用程序并填充表单,提交表单你将会看到employee所有的值,如下图所示:
|
方法 |
描述 |
| View() |
使用默认视图来渲染,例如:如果一个action方法是List并且你使用了没有参数View()方法,List.cshtml视图被呈现 |
| View("name_of_view") |
这个版本在参数中传递一个视图名称并且呈现该视图,例如如果你使用View("Show"),然而你Show.cshtml视图将被呈现 |
|
View(model) |
这个版本给默认视图提提供model数据,这个通常被使用在View中呈现强类型 |
| View("name_of_view",model) |
指定一个视图的名称并且给指定的视图提供model数据 |
using Microsoft.AspNetCore.Mvc;
namespace AspNetCore.Action.Controllers
{
public class ExampleController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult ViewBagExample()
{
ViewBag.CurrentDateTime = DateTime.Now;
ViewBag.CurrentYear = DateTime.Now.Year;
return View();
}
}
}
我们需要注意如下几点:public IActionResult TempDataExample()
{
TempData["CurrentDateTime"] = DateTime.Now;
TempData["CurrentYear"] = DateTime.Now.Year;
return RedirectToAction("TempDataShow");
}
public IActionResult TempDataShow()
{
return View();
}
TempDataExample方法给TempData添加当前时间和当年年份<h2>
Current DateTime & Year: @TempData["CurrentDateTime"] and @TempData["CurrentYear"]
</h2>
TempData按照字典的方式存储值,通过键值对的方式访问,运行程序,https://localhost:7019/Example/TempDataExample,显示当前时间和年份
public IActionResult SessionExample()
{
HttpContext.Session.SetString("CurrentDateTime", DateTime.Now.ToString());
HttpContext.Session.SetInt32("CurrentYear", DateTime.Now.Year);
return View();
}
SetString()方法将添加任何类型作为字符创存储在Session变量中,类似的SetInt32()方法将添加Int值,我们将当前时间和当前年份添加到Session中@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
<h2>
Current DateTime & Year:
@HttpContextAccessor.HttpContext.Session.GetString("CurrentDateTime"),
@HttpContextAccessor.HttpContext.Session.GetInt32("CurrentYear")
</h2>
我们使用依赖注入指令将服务注入到视图中,我们使用该服务能够访问我们Session中存储的值@HttpContextAccessor.HttpContext.Session.GetString("CurrentDateTime"),
@HttpContextAccessor.HttpContext.Session.GetInt32("CurrentYear")
在Session中可以存储复杂类型的变量,例如类,你必须把类序列化成JSON,然后获取该值是再反序列化,我们添加一个新的类:using System.Text.Json;
namespace AspNetCore.Action.Models
{
public static class SessionExtensions
{
public static void Set<T>(this ISession session, string key, T value)
{
session.SetString(key, JsonSerializer.Serialize(value));
}
public static T? Get<T>(this ISession session, string key)
{
var value = session.GetString(key);
return value == null ? default : JsonSerializer.Deserialize<T>(value);
}
}
}
现在在action方法序列化一个类对象,并且将该对象存储到session中,我们使用刚才类里面定义的序列化方法HttpContext.Session.Set<Employee>("Employee", new Employee
{
Name = "KK",
Address= "Tokyo"
});
在视图中我们将json反序列成对象@{
var employee = HttpContextAccessor.HttpContext.Session.Get<Employee>("Employee");
<p>@employee.Name, @employee.Address</p>
}
我们可以在services.AddSession()方法中设置cookie的名字和过期时间,具体代码如下:builder.Services.AddSession(sessionOption =>
{
sessionOption.Cookie.Name = ".myapp";
sessionOption.IdleTimeout= TimeSpan.FromSeconds(10);
});
四. Action方法的调转方式public RedirectResult RedirectAction()
{
return Redirect("/List/Search");
}
RedirectPermanentpublic RedirectResult RedirectPermanentAction()
{
return RedirectPermanent("/List/Search");
}
RedirectToRoutepublic RedirectToRouteResult Redirect()
{
return RedirectToRoute(new { controller = "Admin", action = "Users", ID = 10 });
}
RedirectToRoutePermanentpublic RedirectToRouteResult RedirectPermanent()
{
return RedirectToRoutePermanent(new { controller = "Admin", action = "Users", ID = 10 });
}
RedirectToActionpublic IActionResult Index()
{
return RedirectToAction("Privacy");
}
我们将Index方法调转到相同控制器下的Privacy方法,在这种情况下调转的地址为 -/Home/Privacy,如何调用相同控制器下的action?使用RedirectToAction方法单个参数的重载,这个参数提供了相同控制器下的action方法的名称。如何调用不同控制器下的action方法?你也可以使用RedirectToAction方法2个参数的重载,第一个参数指定控制器的名称,第二个参数指定了控制器中action方法的名称。
public RedirectToActionResult Index()
{
return RedirectToAction("Customer", "List");
}
这种情况下调转的url是/Customer/List 。public IActionResult Index()
{
//return RedirectToAction("Privacy");
return RedirectToActionPermanent("Privacy");
}
五.Action方法返回不同类型的Contentpublic JsonResult ReturnJson()
{
return Json(new[] { "Brahma", "Vishnu", "Mahesh" });
}
在Views->Example文件夹下创建一个ReturnJson.cshtml的视图并显示JSON文件。
public StatusCodeResult ReturnBadRequest()
{
return StatusCode(StatusCodes.Status400BadRequest);
}
例子:返回Unauthorized-401 Status Codepublic StatusCodeResult ReturnUnauthorized()
{
return StatusCode(StatusCodes.Status401Unauthorized);
}
例子:返回NotFound -404 Status Codepublic StatusCodeResult ReturnNotFound()
{
return StatusCode(StatusCodes.Status404NotFound);
}
总结