Open Closed

How to reference Model in 'index.cshtml' #10479


0
timmackey created

ANZ VERSION 8.1.0 angular/.NET Core

Web.Public project file 'Views/Shared/Components/Header/Default.cshtml' refrences Model <img src="@Model.GetLogoUrl(ApplicationPath)" alt="" height="38" />

When I copy the above code to 'Views/Home/index.cshtml', I get 'HTTP ERROR 500' in the browser, and the browser console message is 'VM10:7374 crbug/1173575, non-JS module files deprecated.' error.

How can I refrence 'Model' in 'Views/Home/Index.cshtml'?


8 Answer(s)
  • 0
    ismcagdas created
    Support Team
  • 0
    timmackey created

    Your reply does not answer my question. Please don't say "do it like this". That doesn't work. How is Model passed to index.cshtml? Show me code that will compile and execute without errors.

  • 0
    ismcagdas created
    Support Team

    Hi @timmackey

    Actaully, your question is not related to AspNet Zero. It is related to basics of ASP.NET Core. You can take a look at ASP.NET Core's related documentation for more details.

    Basically it works like this;

    1. You need to create a model class in your Web.Public project;
    public class Product
    {
        public int Id { get; set; }
        
        public string Name { get; set; }
    }
    
    1. Then, in your related controller, you can pass it to your ViewModel;
    public class ProductsController : Controller
    {
        public ProductsController()
        {
            
        }
        
        public async Task<IActionResult> Index()
        {
            var product = new Product(){
                Id = 1,
                Name = "Test Product"
            };
    
            return View(product);
        }
    }    
    
    1. After all, you can access this object in your cshtml file;
    @model Product
    
    <h1>Product Details</h1>
    
    <p>Id:  @Html.DisplayNameFor(model => model.Id)</p>
    <p>Name:  @Html.DisplayNameFor(model => model.Name)</p>
    
    
  • 0
    timmackey created

    I think you are not understanding my question. I will try again.

    I've read ASP.NET Core's documentation and do not understand what to do in this case. I rely on ANZ support for what appears to me to be a trivial question given ANZ's level of expertise. This is not a "how to" question for a generic case, but rather specific to the way ANZ has implemented the main page.

    In ANZ Version 8.1.0, angular/.NET Core there exists in Web.Public project a file 'Views/Shared/Components/Header/Default.cshtml' which refrences Model thusly: <a target = "_blank" rel="noopener noreferrer" title="" href="@Model.GetLogoUrl(ApplicationPath)"><img src="@Model.GetLogoUrl(ApplicationPath)" alt=""></a>

    I want to refrence the exact same 'Model' in the file 'Views/Home/Index.cshtml' ANZ Version 8.1.0 --- not some theoretical file or model I might create. Specifically, I want insert this code: <a target = "_blank" rel="noopener noreferrer" title="" href="@Model.GetLogoUrl(ApplicationPath)"><img src="@Model.GetLogoUrl(ApplicationPath)" alt=""></a> into file 'Views/Home/index.cshtml' ANZ Version 8.1.0 and have it work.

    Please provide the appropriate code that I can use to build ANZ Version 8.1.0 Web.Public project and it will just work with the change described.

  • 0
    ismcagdas created
    Support Team

    Hi @timmackey

    The Model in HeaderViewComponent is scoped to this componetn only. If you only want to use this exact same model in Home page, you can create the same model as we do in https://github.com/aspnetzero/aspnet-zero-core/blob/dev/aspnet-core/src/MyCompanyName.AbpZeroTemplate.Web.Public/Views/Shared/Components/Header/HeaderViewComponent.cs#L51 and pass it to HomeController's Index view.

    So, basically, you can't access the exact same model, but you can pass same data to your view.

  • 0
    timmackey created

    /Views/Home/index.cshtml does not have a HomeController that I am aware of. If a HomeController were to be created, what folder would it be in? What would the contents (code) be? How would it integrate with the existing home page?

    Again, I ask again that you provide code of how this is done, rather than a description of what to do.

    This will be my fourth attempt to get the answer I am requesting. I don't understand why this simple request continues to go unanswered. Is there a language translation problem? Please consider passing this issue to another developer and let them take a swing at it.

  • 0
    ismcagdas created
    Support Team

    Hi Tim,

    This is the mentioned HomeController, see https://github.com/aspnetzero/aspnet-zero-core/blob/dev/aspnet-core/src/MyCompanyName.AbpZeroTemplate.Web.Public/Controllers/HomeController.cs.

    Unfortunately, we can't provide a working sample for every request but I think our instructions are very clear about your question.

  • 0
    timmackey created

    I have successfully applied the code sample you sent via email. Thank you.

    For anyone else who might be experiencing a similar issue, I am posting the solution here.

    HomeController.cs

    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Abp.Application.Navigation;
    using Abp.Configuration;
    using Abp.Configuration.Startup;
    using Abp.Extensions;
    using Abp.Localization;
    using Abp.Runtime.Session;
    using Microsoft.AspNetCore.Mvc;
    using MyCompanyName.AbpZeroTemplate.Configuration;
    using MyCompanyName.AbpZeroTemplate.MultiTenancy;
    using MyCompanyName.AbpZeroTemplate.Sessions.Dto;
    using MyCompanyName.AbpZeroTemplate.Url;
    using MyCompanyName.AbpZeroTemplate.Web.Controllers;
    using MyCompanyName.AbpZeroTemplate.Web.Public.Startup;
    using MyCompanyName.AbpZeroTemplate.Web.Session;
    
    namespace MyCompanyName.AbpZeroTemplate.Web.Public.Controllers
    {
        public class HomeController : AbpZeroTemplateControllerBase
        {
            private readonly IUserNavigationManager _userNavigationManager;
            private readonly IMultiTenancyConfig _multiTenancyConfig;
            private readonly IAbpSession _abpSession;
            private readonly ILanguageManager _languageManager;
            private readonly ISettingManager _settingManager;
            private readonly IPerRequestSessionCache _sessionCache;
            private readonly IWebUrlService _webUrlService;
            private readonly TenantManager _tenantManager;
    
            public HomeController(
                IUserNavigationManager userNavigationManager, 
                IMultiTenancyConfig multiTenancyConfig,
                IAbpSession abpSession,
                ILanguageManager languageManager, 
                ISettingManager settingManager, 
                IPerRequestSessionCache sessionCache,
                IWebUrlService webUrlService, 
                TenantManager tenantManager)
            {
                _userNavigationManager = userNavigationManager;
                _multiTenancyConfig = multiTenancyConfig;
                _abpSession = abpSession;
                _languageManager = languageManager;
                _settingManager = settingManager;
                _sessionCache = sessionCache;
                _webUrlService = webUrlService;
                _tenantManager = tenantManager;
            }
            
            public async Task<ActionResult> Index(string currentPageName = "")
            {
                var tenancyName = "";
                if (_abpSession.TenantId.HasValue)
                {
                    var tenant = await _tenantManager.GetByIdAsync(_abpSession.GetTenantId());
                    tenancyName = tenant.TenancyName;
                }
    
                var model = new PublicHomeIndexViewModel
                {
                    LoginInformations = await _sessionCache.GetCurrentLoginInformationsAsync(),
                    IsInHostView = !_abpSession.TenantId.HasValue,
                    Languages = _languageManager.GetActiveLanguages().ToList(),
                    CurrentLanguage = _languageManager.CurrentLanguage,
                    Menu = await _userNavigationManager.GetMenuAsync(FrontEndNavigationProvider.MenuName, _abpSession.ToUserIdentifier()),
                    CurrentPageName = currentPageName,
                    IsMultiTenancyEnabled = _multiTenancyConfig.IsEnabled,
                    TenantRegistrationEnabled = await _settingManager.GetSettingValueAsync<bool>(AppSettings.TenantManagement.AllowSelfRegistration),
                    AdminWebSiteRootAddress = _webUrlService.GetServerRootAddress(tenancyName).EnsureEndsWith('/'),
                    WebSiteRootAddress = _webUrlService.GetSiteRootAddress(tenancyName).EnsureEndsWith('/')
                };
    
                
                return View(model);
            }
        }
        
        public class PublicHomeIndexViewModel
        {
            public GetCurrentLoginInformationsOutput LoginInformations { get; set; }
    
            public IReadOnlyList<LanguageInfo> Languages { get; set; }
    
            public LanguageInfo CurrentLanguage { get; set; }
    
            public UserMenu Menu { get; set; }
    
            public string CurrentPageName { get; set; }
    
            public bool IsMultiTenancyEnabled { get; set; }
    
            public bool TenantRegistrationEnabled { get; set; }
    
            public bool IsInHostView { get; set; }
    
            public string AdminWebSiteRootAddress { get; set; }
    
            public string WebSiteRootAddress { get; set; }
    
            public string GetShownLoginName()
            {
                if (!IsMultiTenancyEnabled)
                {
                    return LoginInformations.User.UserName;
                }
    
                return LoginInformations.Tenant == null
                    ? ".\\" + LoginInformations.User.UserName
                    : LoginInformations.Tenant.TenancyName + "\\" + LoginInformations.User.UserName;
            }
    
            public string GetLogoUrl(string appPath)
            {
                if (!IsMultiTenancyEnabled || LoginInformations?.Tenant?.LogoId == null)
                {
                    return appPath + "Common/Images/app-logo-on-light.svg";
                }
    
                return AdminWebSiteRootAddress.EnsureEndsWith('/') + "TenantCustomization/GetLogo?tenantId=" + LoginInformations?.Tenant?.Id;
            }
        }
    }
    

    index.cshtml

    @using System.Threading.Tasks
    @using MyCompanyName.AbpZeroTemplate.Web.Public.Startup
    @using CultureHelper = MyCompanyName.AbpZeroTemplate.Localization.CultureHelper
    @model MyCompanyName.AbpZeroTemplate.Web.Public.Controllers.PublicHomeIndexViewModel
    @{
        ViewBag.CurrentPageName = FrontEndPageNames.Home;
    }
    @section Styles
    {
        <link rel="stylesheet" href="~/assets/fancybox/source/jquery.fancybox.css" asp-append-version="true">
        <link rel="stylesheet" href="~/lib/owl.carousel/dist/assets/owl.carousel.css" asp-append-version="true">
    }
    @section Scripts
    {
        <script src="~/assets/fancybox/source/jquery.fancybox.pack.js" type="text/javascript"></script><!-- pop up -->
        <script src="~/lib/owl.carousel/dist/owl.carousel.js" type="text/javascript"></script><!-- slider for products -->
        <script type="text/javascript">
            $(function () {
                Layout.initOWL();
            });
        </script>
    }
    
    <h1>
        WebSiteRootAddress:
    </h1>
    <h2>
        @Model.WebSiteRootAddress
    </h2>
    <h1>
        AdminWebSiteRootAddress:
    </h1>
    <h2>
        @Model.AdminWebSiteRootAddress
    </h2>
    <!-- BEGIN SERVICE BOX -->
    <div class="row service-box margin-bottom-40">
    .
    .
    .
    </div>
    <!-- END SERVICE BOX -->
    <!-- BEGIN BLOCKQUOTE BLOCK -->
    <div class="row quote-v1 margin-bottom-30">
        <div class="col-md-12">
            <span>ASP.NET Iteration Zero - Starting point for your next web project!</span>
        </div>
    </div>
    <!-- END BLOCKQUOTE BLOCK -->
    <!-- BEGIN RECENT WORKS -->
    <div class="row recent-work margin-bottom-40">
    .
    .
    .
    </div>
    <!-- END RECENT WORKS -->
    <!-- BEGIN TABS AND TESTIMONIALS -->
    <div class="row mix-block margin-bottom-40">
        <!-- TABS -->
        <div class="col-md-7 tab-style-1">
    	.
    	.
    	.
        </div>
        <!-- END TABS -->
        <!-- TESTIMONIALS -->
        <div class="col-md-5 testimonials-v1">
    	.
    	.
    	.
        </div>
        <!-- END TESTIMONIALS -->
    </div>
    <!-- END TABS AND TESTIMONIALS -->
    <!-- BEGIN STEPS -->
    <div class="row margin-bottom-40 front-steps-wrapper front-steps-count-3">
    .
    .
    .
    </div>
    <!-- END STEPS -->
    <!-- BEGIN CLIENTS -->
    <div class="row margin-bottom-40 our-clients">
    .
    .
    .
    </div>
    <!-- END CLIENTS -->