阅读 92

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请求获取图片




    
    


    Al


 上传文件控制器

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);
        }
    

 

向客户端输出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";
}

Index

@Html.Action("GetPartial")

 

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

_Login.cshtml 分部页面内容




  


@{
ViewBag.Title = "Index";
}

Index

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

  

  

 

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

文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐