且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET中Html.Partial和Html.Action的一个区别

更新时间:2022-09-27 11:03:00

Html.Partial通常呈现的是静态内容,如果不指定的Partial方法中绑定的参数,默认为宿主页面的Model类型,因此如果Partial页面中的Model和主页面的Model类型不一致的话,一定要指定 Partial方法中绑定的参数,不然会报错。Html.Partial方法也不会触发Action方法。

Html.Action会调用Action方法,并且会返回一个View或者PartialView,或者Json等(根据具体Action中返回的值)

因此,如果使用不同的Model,可以考虑使用Html.Action来处理。下面是部分代码演示。



  1. @model MvcApplication1.Views.Test2.Test2_Index  
  2. @{  
  3.     ViewBag.Title = "Index";  
  4. }  
  5.  
  6. <h2>Test2-Index</h2> 
  7. @Model.i<br /> 
  8.  
  9. @***不触发action方法,PartialIndex.cshtml中绑定  
  10. 了Model和Index.cshtml绑定的Model不一样,  
  11. 因此必须指定自己的Model,否则报错。  
  12. *@  
  13.  
  14. @Html.Partial("PartialIndex",new MvcApplication1.Views.Test2.Test2_ParitalIndex())<br /> 
  15.  
  16. @*  
  17. **触发action方法,不指定Model的时候就传入一个新的Test2_ParitalIndex对象
  18. *@  
  19. @Html.Action("PartialIndex", "Test2")<br /> 

 


  1. @model MvcApplication1.Views.Test2.Test2_ParitalIndex  
  2. TestPartial<br /> 
  3. @Model.i<br /> 

 


  1. public class Test2Controller : Controller  
  2. {  
  3.     public ActionResult Index(Test2_Index vm)  
  4.     {  
  5.         return View("Index",vm);  
  6.     }  
  7.  
  8.     public ActionResult PartialIndex(Test2_ParitalIndex vm)  
  9.     {  
  10.         return View("PartialIndex", vm);  
  11.     }  

 


对于 下列这种方法,


  1. public ActionResult Index(Test2_Index vm)  
  2.         {  
  3.             return View("Index",VM);  
  4.         } 

如果Action方法Get请求的时候,没有设置绑定参数,则vm会得到一个默认想new

Test2_Index ()对象。如果设置了绑定参数,则按照设定值传递给Action方法。










本文转自cnn23711151CTO博客,原文链接: http://blog.51cto.com/cnn237111/1032013,如需转载请自行联系原作者