当前位置: 首页> 娱乐> 明星 > 沧州网站建设开发服务_邢台做网站多少钱_网络营销工作内容和职责_如何免费找精准客户

沧州网站建设开发服务_邢台做网站多少钱_网络营销工作内容和职责_如何免费找精准客户

时间:2025/8/8 21:29:56来源:https://blog.csdn.net/weixin_42067536/article/details/144279941 浏览次数:0次
沧州网站建设开发服务_邢台做网站多少钱_网络营销工作内容和职责_如何免费找精准客户

文章目录

  • 项目地址
  • 一、MVC的传值方式
    • 1.1 ViewBag和ViewData传值
      • 1.1.1 ViewBag
      • 1.1.2 ViewData
    • 1.2 视图模型传值(ViewModel)
  • 二、HttpConntext上下文
  • 三、中间件


项目地址

  • 教程作者:誉尚学教育
  • 教程地址:
https://www.bilibili.com/video/BV1TU4y1z7kM?spm_id_from=333.788.player.switch&vd_source=791e6deaa9c8a56b1f845a0bc1431b71&p=11
  • 代码仓库地址:
  • 所用到的框架和插件:
.net

一、MVC的传值方式

1.1 ViewBag和ViewData传值

1.1.1 ViewBag

  • 临时存储,且不能跨页面和跨视图传递
  1. 在controller里传递数据
public class HomeController : Controller
{public ActionResult Index(){ViewBag.Message = "Welcome to ASP.NET MVC!";ViewBag.CurrentDate = DateTime.Now.ToString("yyyy-MM-dd");return View();}
}
  1. 在View页面使用
<!DOCTYPE html>
<html>
<head><title>@ViewBag.Title</title>
</head>
<body><h1>@ViewBag.Message</h1><p>Today's date is: @ViewBag.CurrentDate</p>
</body>
</html>

1.1.2 ViewData

  1. Controller
public class HomeController : Controller
{public ActionResult Index(){ViewData["Message"] = "Welcome to ASP.NET MVC!";ViewData["CurrentDate"] = DateTime.Now.ToString("yyyy-MM-dd");return View();}
}
  1. View
<!DOCTYPE html>
<html>
<head><title>@ViewData["Title"]</title>
</head>
<body><h1>@ViewData["Message"]</h1><p>Today's date is: @ViewData["CurrentDate"]</p>
</body>
</html>

1.2 视图模型传值(ViewModel)

1.使用Action的View()方法传递视图模型,传递什么类型,View里就是什么类型

public class ProductController : Controller
{public IActionResult Index(){// 创建一个产品列表var products = new List<ProductViewModel>{new ProductViewModel { Id = 1, Name = "Laptop", Price = 1200.50, Category = "Electronics" },new ProductViewModel { Id = 2, Name = "Phone", Price = 800.00, Category = "Electronics" },new ProductViewModel { Id = 3, Name = "Tablet", Price = 300.00, Category = "Electronics" }};// 将列表传递到视图return View(products);}
}
  1. 在View里使用,小写model 并且需要根据类型来取值
@model List<ProductViewModel><tbody>@foreach (var product in Model){<tr><td>@product.Id</td><td>@product.Name</td><td>@product.Price</td><td>@product.Category</td></tr>}
</tbody>

注意:①如果IActionResult 返回的是明确的类型,如类,或者集合,他就会默认View视图里;②如果传递的是其他的路由,他就会跳转到其他路由

二、HttpConntext上下文

在mvc中,但凡要创建对象,优先考虑从容器中拿对象,这样不用考虑他的创建过程需要什么参数
只有在创建Model层的时候,才考虑直接New一个对象出来

三、中间件

  • 中间件是一个从发起请求到返回结果的过程,所以,所有的请求都是通过中间件,参与完成的。
关键字:沧州网站建设开发服务_邢台做网站多少钱_网络营销工作内容和职责_如何免费找精准客户

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: