کانال بله, جهت پشتیبانی و اطلاع رسانی کانال بله, جهت پشتیبانی و اطلاع رسانی
عضویت

آموزش MVC Core-آموزش ایجاد Mvc View Component در MVC Core

آموزش MVC Core-آموزش ایجاد Mvc View Component در MVC Core

مشکل

نحوه استفاده از بخش های "web pages" با استفاده از "View Components" در ASP.NET Core MVC.

راه حل

در یک پروژه خالی، کلاس "Startup" را به روزرسانی کنید تا "services" و "middleware" برای MVC اضافه شود.

public void ConfigureServices(  
    IServiceCollection services)  
{  
    services.AddScoped< IAddressFormatter, AddressFormatter >();  
    services.AddMvc();  
}  
  
public void Configure(  
    IApplicationBuilder app,  
    IHostingEnvironment env)  
{  
    app.UseMvc(routes = >  
    {  
        routes.MapRoute(  
            name: "default",  
            template: "{controller=Home}/{action=Index}/{id?}");  
    });  
}  

یک «مدل» برای نمایش در «View» اضافه کنید.

public class EmployeeViewModel  
 {  
     public int Id { get; set; }  
     public string Firstname { get; set; }  
     public string Surname { get; set; }  
 }  

یک "کنترلر " را با "action method" اضافه کنید که "ViewResult" را بازگرداند.

public IActionResult Index()  
   {  
       var model = new EmployeeViewModel  
       {  
           Id = 1,  
           Firstname = "James",  
           Surname = "Bond"  
       };  
       return View(model);  
   }  

یک "parent View" را با نام Index.cshtml اضافه کنید.

@using Fiver.Mvc.ViewComponents.Models.Home  
@model EmployeeViewModel  
   
< div style="border: 1px solid black; margin: 5px" >  
    < strong >Employee Details (view)< /strong >  
   
    < p >Id: @Model.Id< /p >  
    < p >Firstname: @Model.Firstname< /p >  
    < p >Surname: @Model.Surname< /p >  
   
    @await Component.InvokeAsync("Address", new { employeeId = Model.Id })  
< /div >  
   
@await Component.InvokeAsync("UserInfo") 

یک مدل "View Component’s" را اضافه کنید.

public class AddressViewModel  
 {  
     public int EmployeeId { get; set; }  
     public string Line1 { get; set; }  
     public string Line2 { get; set; }  
     public string Line3 { get; set; }  
     public string FormattedValue { get; set; }  
 }  

یک کلاس "View Component’s" را اضافه کنید.

[ViewComponent(Name = "Address")]  
  public class AddressComponent : ViewComponent  
  {  
      private readonly IAddressFormatter formatter;  
  
      public AddressComponent(IAddressFormatter formatter)  
      {  
          this.formatter = formatter;  
      }  
  
      public async Task InvokeAsync(int employeeId)  
      {  
          var model = new AddressViewModel  
          {  
              EmployeeId = employeeId,  
              Line1 = "Secret Location",  
              Line2 = "London",  
              Line3 = "UK"  
          };  
          model.FormattedValue =   
              this.formatter.Format(model.Line1, model.Line2, model.Line3);  
          return View(model);  
      }  
  }  

یک View برای Component’s View ایجاد و نام آن را Default.cshtml بنویسید:

@using Fiver.Mvc.ViewComponents.Models.Home  
@model AddressViewModel  
   
< div style="border: 1px dashed red; margin: 5px" >  
    < strong >Address Details (view component in Views/Home)< /strong >  
   
    < p >Employee: @Model.EmployeeId< /p >  
    < p >Line1: @Model.Line1< /p >  
    < p >Line2: @Model.Line2< /p >  
    < p >Line3: @Model.Line3< /p >  
    < p >Full Address: @Model.FormattedValue< /p >  
< /div > 

مباحثه

"View Components" نوع خاصی از "Views" ارائه شده در داخل "Views" دیگر است. آنها برای استفاده مجدد از قسمت های یک " View" یا تقسیم " View " های بزرگ به اجزای کوچکتر مفید هستند.
بر خلاف (Partial Views) ها، (View Components) بر روی "Controllers" تکیه نمی کند. آنها کلاس خود را برای پیاده سازی منطق برای ساخت مدل جزء و صفحه نمایش Razor View برای نمایش HTML / CSS دارند.
من دوست دارم از آنها به عنوان mini-controllers فکر کنم، اگرچه این کاملا دقیق نیست اما به مفاهیم استفاده از آنها کمک می کند. برخلاف " Controllers ها"، آنها "درخواست HTTP" را نادیده نمی گیرند و یا " Controller lifecycle " دارند، به این معنی که نمی توانند به فیلتر یا " model binding" تکیه کنند.
"View Components" می تواند از " dependency injection" استفاده کند که باعث می شود آنها قدرتمند و قابل تست باشند.

پدید آوردن

چند راه برای ایجاد " View Components " وجود دارد:

  • یک کلاس (در هر جا از پروژه خود) ایجاد کنید که از کلاس ViewComponent abstract به ارث برده شود.
    نام کلاس، با توافق، با ViewComponent پایان می یابد.
  • یک روش به نام ()InvokedAsync ایجاد کنید که Task< IViewComponentResult >را بازگرداند.
    این روش می تواند هر تعداد پارامترهایی را که هنگام فراخوانی کامپوننت تصویب می شود را بگیرد
    (در بخش Invoking می توانید مشاهده کنید).
  • ایجاد مدل برای مثال از طریق پایگاه داده و غیره.
  • فراخوانی IviewComponentResult با فراخوانی کردن متد ()View بر اساس ViewComponent. شما می توانید مدل خود را با این روش منتقل کنید.

به صورت اختیاری می توانید نام " razor page " را مشخص کنید (بخش Discovery را در زیر ببینید).
کلاس پایه "ViewComponent" دسترسی به جزئیات مفید را (از طریق properties) مانند HttpContext، RouteData، IUrlHelper، IPrincipal و ViewData را می دهد.

Invoking(فراخوانی)

View Componentsرا می توان با دو روش زیر فرخوانی کرد:

  1. فراخوانیawait Component.InvokeAsync@ (component ، parameters) از razor view.
  2. بازگشت ViewComponent (component ، parameters) از یک کنترلر.

در اینجا، " component " یک مقدار رشته ای است که به کلاس component ارجاع داده می شود.
روش ()InvokeAsync می تواند هر تعداد پارامتر را بگیرد و هنگام فراخوانی « ViewComponent » با استفاده از یک شی " anonymous object " منتقل می شود.
در زیر یک مثال از گزینه دوم در بالا است. توجه داشته باشید که روش دوم عمل نمی کند زیرا Razor page برای " component " در زیر پوشه Views کنترلر مشاهده نمی شود:

public class ComponentsController : Controller  
 {  
     public IActionResult UserInfo()  
     {  
         // works: this component's view is in Views/Shared  
         return ViewComponent("UserInfo");  
     }  
  
     public IActionResult Address()  
     {  
         // doesn't works: this component's view is NOT in Views/  
         return ViewComponent("Address", new { employeeId = 5 });  
     }  
 } 

پژوهش(Discovery)

MVC برای " razor page" برای " View Component" در توالی زیر جستجو خواهد کرد:

  1. Views/[controller]/Components/[component]/[view].cshtml
  2. Views/Shared/Components/[component]/[view].cshtml

در اینجا اینا هم همخوانی دارند:

  1. نام کلاس component ، منهای پسوند ViewComponent اگر استفاده شود.
  2. مقدار مشخص شده در ویژگی [ViewComponent] اعمال شده به کلاس component.

همچنین، [view] به طور پیش فرض Default.cshtml است، با این حال، با بازگشت یک نام دیگر از کلاس component ، می توان آن را تغییر داد.در زیر component یک view به نام Info.cshtml باز می گرداند:

public class UserInfoViewComponent : ViewComponent  
 {  
     public async Task InvokeAsync()  
     {  
         var model = new UserInfoViewModel  
         {  
             Username = "james@bond.com",  
             LastLogin = DateTime.Now.ToString()  
         };  
         return View("info", model);  
     }  
 } 

jQuery

شما همچنین می توانید به "View Components" از طریق jQuery دسترسی پیدا کنید.برای انجام این کار استفاده از "Static Files" را در "Startup" فعال کنید.

public void Configure(  
      IApplicationBuilder app,  
      IHostingEnvironment env)  
  {  
      app.UseStaticFiles();  
      app.UseMvc(routes =>  
      {  
          routes.MapRoute(  
              name: "default",  
              template: "{controller=Home}/{action=Index}/{id?}");  
      });  
  }  

اضافه کردن "فایل اسکریپت جی کوئری" به wwwroot و استفاده از آن در صفحه:

< html >  
< head >  
    < meta name="viewport" content="width=device-width" / >  
    < title >ASP.NET Core View Components< /title >  
   
    < script src="~/js/jquery.min.js" >< /script >  
   
< /head >  
< body >  
    < div >  
        < strong >ASP.NET Core View Components< /strong >  
   
        < input type="button" id="GetViewComponent" value="Get View Component" / >  
   
        < div id="result" >< /div >  
    < /div >  
    < script >  
        $(function () {  
            $("#GetViewComponent").click(function () {  
   
                $.ajax({  
                    method: 'GET',  
                    url: '@Url.Action("UserInfo", "Components")'  
                }).done(function (data, statusText, xhdr) {  
                    $("#result").html(data);  
                }).fail(function (xhdr, statusText, errorText) {  
                    $("#result").text(JSON.stringify(xhdr));  
                });  
   
            });  
        });  
    < /script >  
< /body >  
< /html > 

شما می توانید Source Code این مقاله را از لینک زیر دانلود کنید:

https://github.com/TahirNaushad/Fiver.Mvc.ViewComponents

شما دانشجویان گرامی می توانید فایل مربوط به این آموزش را از قسمت پایانی این مقاله دانلود نمایید .

1397/03/08 4256 2060
رمز عبور : tahlildadeh.com یا www.tahlildadeh.com
نظرات شما

نظرات خود را ثبت کنید...