【发布时间】:2021-03-15 06:28:59
【问题描述】:
我想在我的项目的多个页面上使用相同的联系表单。
我在一个名为 FormInViewComponent 的示例项目上进行了尝试,如下所示:
Controllers > TestController.cs
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FormInViewComponent.Controllers
{
public class TestController : Controller
{
public IActionResult Index()
{
return View();
}
}
}
Views > Test > Index.cshtml(我在这个页面上调用了ViewComponent)
@model FormModel
<div class="container">
<div class="row">
<div class="col-8">
<h3>Page content is here</h3>
</div>
<div class="col-4 bg-light p-3">
@await Component.InvokeAsync("SampleForm")
</div>
</div>
</div>
Models > FormModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace FormInViewComponent.Models
{
public class FormModel
{
[Required]
public string Name { get; set; }
}
}
ViewComponents > SampleFormViewComponent.cs
using FormInViewComponent.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FormInViewComponent.ViewComponents
{
public class SampleFormViewComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync(FormModel formModel)
{
return await Task.FromResult(View(formModel));
}
}
}
Views > Shared > Components > SampleForm > Default.cshtml
@model FormModel
<h4>ViewComponent is here</h4>
<b class="text-info">Sample Form</b>
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="col-12">
<div class="form-group">
<label asp-for="Name"></label><br />
<input type="text" asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<p class="text-center">
<input class="btn btn-success" type="submit" value="Send" />
</p>
</div>
</form>
【问题讨论】:
-
除此之外,您能否编辑您的问题以包括对什么不起作用的解释?例如,您是否遇到了异常——如果是,那是什么?根据您的代码,我的假设是您没有收到错误,而且您的表单没有呈现,因为
Component.InvokeAsync()的问题往往会默默地失败。如果是这样,这将有助于受访者知道。同时,我根据我期望通过您的代码阅读的内容提供了一个答案。
标签: asp.net-core asp.net-core-3.1 asp.net-core-viewcomponent view-components