Templating in ASP.Net Core

2019-07-17 03:03发布

问题:

I have a problem creating a "sub"-template in asp.net core. The idea is to define a complete html-bootstrap-block in a template file and call it in another parent/master cshtml file.

ViewModel Person (filled in the controller)

namespace RazorTemplating.Models.HomeViewModels
{
    public class Person
    {
        [Required]
        [MinLength(2)]
        public string Firstname { get; set; }

        [Required]
        [MinLength(2)]
        public string Lastname { get; set; }

        [MaxLength(3)]
        public int Age { get; set; }

        public Group MainGroup { get; set; }
    }
}

The master view called by the controller (Index.cshtml)

Edit: The input-template-tags reference a custom tag helper.

@model RazorTemplating.Models.HomeViewModels.Person

<div class="row">
    <input-template for="Firstname" />
</div>
<div class="row">
    <input-template for="Lastname" />
</div>
<div class="row">
    <input-template for="Age" />
</div>
<div class="row">
    <input-template for="MainGroup" />
</div>

Inputbox Bootstrap template file (InputBootstrapTemplate.cshtml)

@model dynamic

<div class="form-group">
    <label asp-for="@Model" class="col-md-2 control-label"></label>
    <div class="col-md-10">
        <input asp-for="@Model" class="form-control" />
        <span asp-validation-for="@Model" class="text-danger"></span>
    </div>
</div>

How i can fill the dynamic model for template file, from the input-template-tag helper?

Edit: Something is changing in advance for templating in ASP.NET Core https://github.com/aspnet/Razor/issues/788

回答1:

As I understand you want to render something like custom controls. For example, render control with some wrapping html, label, input by one line. Right? In this case tag helpers fit your need very good.

Also you could take a look at new feature - view components. It is like small (one action) controller + view pair. It is good to render blocks, like news, last added comments etc.

Feel free to ask for details.