我想在我的项目的多个页面上使用相同的联系表。
我在一个名为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>