C
C#12mo ago
Alizer

✅ Retain form tag helper names inside partial view

I want to retain a form tag helper's name inside a partial view, I have a massive form model with lots of nested objects, below is just a simplified version of what I wanted to do I have a form below, this works because Name.FirstName is being handled correctly by ASP automatically setting the name of the <input/> tag, my controller parses this correct into a Member object
@model Member
<form>
<div class="form-floating flex-grow-1">
<input asp-for="Name.FirstName" class="form-control border-0 bg-subtle" placeholder="name@example.com">
<label asp-for="Name.FirstName">
<i class="fa-solid fa-person me-2"></i>First Name
</label>
<span asp-validation-for="Name.FirstName" class="text-danger fw-normal"></span>
</div>
</form>
@model Member
<form>
<div class="form-floating flex-grow-1">
<input asp-for="Name.FirstName" class="form-control border-0 bg-subtle" placeholder="name@example.com">
<label asp-for="Name.FirstName">
<i class="fa-solid fa-person me-2"></i>First Name
</label>
<span asp-validation-for="Name.FirstName" class="text-danger fw-normal"></span>
</div>
</form>
but since my form is massive, I wanted to split it to multiple sections, now I put the Name property inside another partial view like below
// _NameSection.cshtml partial view
@model Name
<div class="form-floating flex-grow-1">
<input asp-for="FirstName" class="form-control border-0 bg-subtle" placeholder="name@example.com">
<label asp-for="FirstName">
<i class="fa-solid fa-person me-2"></i>First Name
</label>
<span asp-validation-for="FirstName" class="text-danger fw-normal"></span>
</div>
// _NameSection.cshtml partial view
@model Name
<div class="form-floating flex-grow-1">
<input asp-for="FirstName" class="form-control border-0 bg-subtle" placeholder="name@example.com">
<label asp-for="FirstName">
<i class="fa-solid fa-person me-2"></i>First Name
</label>
<span asp-validation-for="FirstName" class="text-danger fw-normal"></span>
</div>
and below is the main form's .cshtml file
// Main form .cshtml page view
@model Member
<form>
<partial name="_NameSection"/>
</form>
// Main form .cshtml page view
@model Member
<form>
<partial name="_NameSection"/>
</form>
and for some reason this breaks ASP's automatically set name for the <input/> tag, it just sets the input's name to FirstName when it should be Name.FirstName, how do I fix this?
2 Replies
Alizer
Alizer12mo ago
nevermind i plugged this in chatgpt and the correct answer is to pass it to the partial view's for attribute <:picard_facepalm:616692703685509130>
Denis
Denis12mo ago
If this issue is solved, consider using /close to make it as closed