MVC ActionResult 视图模型

ViewResult,ContentResult,RedirectResult,RedirectToRouteResult,FileContentResult,JsonResult,HttpStatusCodeResult,PartialViewResult

[HttpGet]
        public ActionResult Login()
        {

            return View();//返回一个视图页面
        }
[HttpGet]
        public ActionResult Login1()
        {

            return Content("hello");//返回一个字符串
        }
[HttpGet]
        public ActionResult Login()
        {
       //Respones.Redirect 一个封装 
            return Redirect("http://wwww.baidu.com");//重定向
        }
//通过路由跳转到控制器
[HttpGet]
public ActionResult RedirectToAction() { //跳转到Action return RedirectToAction("Login1"); } [HttpGet] public ActionResult RedirectToAction2() { //跳转到指定控制器的Action return RedirectToAction("Index","Student"); }


File()返回文件,有两个参数,一个文件名,一个是内容类型,向客户端输出文件

有多个方法重载

[HttpGet]
public ActionResult GetFile(string filename)
{
string upload = "~/upload";
return File($@"{Server.MapPath(upload)}{filename}", "image/png");
}

可以在Html中使用标签访问,也可以直接get请求获取图片

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <img src="Home/GetFile" alt="Al" width="100" height="40" />
</body>
</html>

 上传文件控制器

string upload = "~/upload";
        [HttpPost]
        public ActionResult UploadFiles(HttpPostedFileBase file)
        {
            if (!Directory.Exists(Server.MapPath(upload)))
            {
                Directory.CreateDirectory(Server.MapPath(upload));
            }
            var filename = DateTime.Now.Ticks + file.FileName;
            file.SaveAs($@"{Server.MapPath(upload)}{filename}");
            return Content(filename);
        }
    <form action="/Home/UploadFiles" enctype="multipart/form-data" method="post">
        <input type="file" name="file" /><button>上传文件</button>
    </form>
    

向客户端输出Json格式数据 

        public ActionResult Json()
        {
            //默认是不支持Get请求的,需要指定允许
            return Json(new { id=1,name="blank"},JsonRequestBehavior.AllowGet);
        }

向客户端输出状态码,状态码状态很多,可以根据实际情况返回

    public ActionResult GetCode()
        {
            return new HttpStatusCodeResult(System.Net.HttpStatusCode.NotFound);
        }

//分部页面

        public ActionResult GetPartial()
        {
            //返回分部页面,类似一个Vue中的组件,可以在需要的地方重复使用
            return PartialView();
        }

可以在前端页面这样调用,类似使用组件

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@Html.Action("GetPartial")

上面演示的带action处理的,还支持静态的页面

_Login.cshtml 分部页面内容

<input type="text"   name="name" value="" />
<input type="password"  name="pwd" value="" />
<button>登录</button>

  


@{
ViewBag.Title = "Index";
}

<h2>Index</h2>

@* 调用Action页面 *@
@Html.Action("GetPartial")
@* 调用静态页面,支持传参到页面 *@
@Html.Partial("_Login",new ASP.NET_MVC基础_2.Models.Student())

  

  

原文地址:https://www.cnblogs.com/ankeyliu/p/15221363.html