asp.net core 태그 조수 의 고급 용법 TagHelper+Form
asp.net core 를 처음 접 한 소 년 에 대해 서 는 TagHelper 에 대한 나의 이해 와 견 해 를 볼 수 있 습 니 다.
<asp.net core 새로운 기능(1):TagHelper>
이후 에 도 저 는 계속해서 박문 을 작성 하여 asp.net core 의 새로운 특성,예 를 들 어 DI,ViewComponent,bower 등 asp.net mvc 에 없 는 새로운 것들 을 공유 할 것 입 니 다.
오케이,우리 시작 합 시다~~
이전에 제 가 TagHelper 에 대한 공유 에서 언급 했 듯 이 TagHelper 는 원래@Html 도움말 류 에 있 던 일부 기능,예 를 들 어 form,a 등 라벨 을 대체 할 수 있 고 html 코드 에 쓰 면 더욱 편안 하 며 html 문법 에 부합 합 니 다.
<!-- form-->
<form asp-controller="Home" asp-action="Index" class="form-horizontal" method="post">
</form>
<!--Html form-->
@using (Html.BeginForm("Index", "Home", FormMethod.Post,, new { Class = "form-horizontal" }))
{
}
그렇다면 Html 도움말 클래스 에서 가장 유용 한 Model 과 Tag 의 전환,자동 폼 생 성,마이크로소프트 도 솔 루 션 을 제시 한 것 일 까?답 은 긍정 적 이다.Microsoft 는 또 별도의 설명 페이지 를 나 누 어 TagHelper 의 자동 폼 생 성 을 설명 했다.영어 실력 이 좋 은 학생 은 MS 의 공식 문 서 를 직접 볼 수 있다《Introduction to using tag helpers in forms in ASP.NET Core》。문서 에서 폼 컨트롤 에 대해 언급 했 습 니 다.asp-for 속성 에 Model 의 속성 명 을 직접 입력 하면 해당 하 는 컨트롤 형식 을 자동 으로 생 성하 고 기본 값 을 입력 할 수 있 습 니 다.
ok,우리 한번 해 보 자.
(1)ViewModel 클래스 만 들 기
public class SignUpViewModel
{
[Required]
[Display(Name =" ")]
[MaxLength(30,ErrorMessage = " 30")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[RegularExpression(@"((?=.*\d)(?=.*\D)|(?=.*[a-zA-Z])(?=.*[^a-zA-Z]))^$",ErrorMessage =" ")]
[Display(Name =" ")]
public string Password { get; set; }
[DataType(DataType.MultilineText)]
public string Description { get; set; }
}
asp.net 뮤 직 비디오 를 쓴 개발 자 에 게 는 낯 설 지 않 을 것 입 니 다~(2)TagHelper 태그 작성
Html 과 구분 하기 위해 서 나 는 두 가지 비교 버 전 을 썼 다.
<form asp-controller="Home" asp-action="SignUp" method="post" class="form-horizontal">
<div class="form-group">
<label asp-for="UserName"></label>
<input asp-for="UserName" />
<span asp-validation-for="UserName"></span>
</div>
<div class="form-group">
@Html.LabelFor(m=>m.Password)
@Html.PasswordFor(m=>m.Password)
@Html.ValidationMessageFor(m=>m.Password)
</div>
<div class="form-group">
<label asp-for="Description"></label>
<textarea asp-for="Description"></textarea>
<span asp-validation-for="Description"></span>
</div>
<div class="form-group">
<input type="submit" value=" " />
<input type="reset" value=" " />
</div>
</form>
(3)검증 폼
public IActionResult SignUp(SignUpViewModel model)
{
if (ModelState.IsValid)
{
return RedirectToAction("Index");
}
else
{
return RedirectToAction("Index",model);
}
}
(4)결과ok,이렇게 끝나 면 TagHelper 고급 애플 리 케 이 션 이 아니 라 MS 문 서 를 번역 할 수 밖 에 없습니다.
그렇다면 중요 한 것 은 MS 가 사용자 정의 TagHelper 를 만 들 수 있다 는 것 이다.그렇다면 나 는 왜 TagHelper 에서 Model 의 값 을 사용 할 수 없 을 까?그래서 저 는 asp.net core 오픈 소스 github 프로젝트 에서 찾기 시 작 했 고 마침내 ImputTagHelper 의 소스 코드 를 찾 았 습 니 다.
원본 코드 에서 세 대상 이 함께 탭 생 성 을 완성 합 니 다.
protected IHtmlGenerator Generator { get; }
[HtmlAttributeNotBound]
[ViewContext]
public ViewContext ViewContext { get; set; }
/// <summary>
/// An expression to be evaluated against the current model.
/// </summary>
[HtmlAttributeName(ForAttributeName)]
public ModelExpression For { get; set; }
세 대상 은 모두 주입 에 의존 하 는 방식 으로 대상 의 생 성 을 실현 한다.(1)그 중에서 Generator 는 발생 기 를 위해 다양한 유형의 라벨 생 성 을 책임 집 니 다.
(2)ViewContext 는 보기 컨 텍스트 로 보기 컨 텍스트 에 관 한 정 보 를 가 져 옵 니 다.
(3)For 현재 Model 의 관련 정 보 를 얻 을 수 있 습 니 다.Required 등 관건 적 인 정 보 를 포함 합 니 다.
이 세 개의 탭 이 있 으 면 저 희 는 사용자 정의 탭 조수 에서 원 하 는 Model 정 보 를 얻 을 수 있 습 니 다.예 를 들 어 저 는 form 에 Model 정 보 를 입력 하여 탭 조수 가 form 폼 의 모든 내용 을 자동 으로 생 성 할 수 있 습 니 다.얼 탭 에 트 리 정 보 를 입력 하여 트 리 목록 을 자동 으로 생 성 할 수도 있 습 니 다.
다음은 제 가 작성 한 자동 생 성 폼 입 니 다.
// bg-form
[HtmlTargetElement("bg-form")]
public class FormTagHelper : TagHelper
{
[ViewContext]
[HtmlAttributeNotBound]
public ViewContext ViewContext { get; set; }
[HtmlAttributeName("asp-for")]
public ModelExpression For { get; set; }
protected IHtmlGenerator Generator { get; }
public FormTagHelper(IHtmlGenerator generator)
{
Generator = generator;
}
[HtmlAttributeName("asp-controller")]
public string Controller { get; set; }
[HtmlAttributeName("asp-action")]
public string Action { get; set; }
//
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "form";
if (!string.IsNullOrWhiteSpace(Controller))
{
output.Attributes.Add("action", "/" + Controller + "/" + Action);
}
output.Attributes.Add("class", "form-horizontal");
//
var props = For.ModelExplorer.Properties;
foreach (var prop in props)
{
//
var div = new TagBuilder("div");
div.AddCssClass("form-group");
var label = Generator.GenerateLabel(ViewContext, prop, null, prop.Metadata.DisplayName, null);
var input = Generator.GenerateTextBox(ViewContext, prop, prop.Metadata.PropertyName, null, null, null);
var span = Generator.GenerateValidationMessage(ViewContext, prop, prop.Metadata.PropertyName, null, ViewContext.ValidationMessageElement, null);
div.InnerHtml.AppendHtml(label);
div.InnerHtml.AppendHtml(input);
div.InnerHtml.AppendHtml(span);
output.Content.AppendHtml(div);
}
//
var btn = new TagBuilder("div");
btn.AddCssClass("form-group");
var submit = new TagBuilder("input");
submit.Attributes.Add("type", "submit");
submit.Attributes.Add("value", " ");
var reset = new TagBuilder("input");
reset.Attributes.Add("type", "reset");
reset.Attributes.Add("value", " ");
btn.InnerHtml.AppendHtml(submit);
btn.InnerHtml.AppendHtml(reset);
output.Content.AppendHtml(btn);
//
output.Content.AppendHtml(await output.GetChildContentAsync());
}
}
html 에 만 가입 하면
<bg-form asp-controller="Home" asp-action="SignUp" asp-for="@Model">
</bg-form>
폼 자동 생 성Over,오늘 TagHelper 에 대해 서 는 여기까지 공유 하 겠 습 니 다.
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
작업 중 문제 해결 - (win 2003 asp. net) Session 과 페이지 전송 방법 으로 해결 방안 을 정상적으로 사용 할 수 없습니다.또한 F 는 처음에 우리 의 BP & IT 프로젝트 팀 이 Forms 폼 검증 을 사용 했다 고 판단 할 수 있 습 니 다. 페이지 를 뛰 어 넘 는 것 은http://hr.bingjun.cc/MyTask/MyTas...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.