crystyxn crystyxn - 4 months ago 10
Javascript Question

Two text html text inputs in two different places on the page with the same submit id

So I have a page called Index.cshtml

I have this input in a form with the id "cvr":

@using (Html.BeginForm("SendMailAsACompany", "Contract", null, FormMethod.Post, new { id = "cvr" }))
{
<input type="hidden" value=@Html.ViewData.Model.StudentId name="studentId" />
<input type="hidden" value=@Html.ViewData.Model.CompanyId name="companyId" />
<input type="hidden" value=@Html.ViewData.Model.ApplicationId name="applicationId"/>


if (User.Identity.GetUserId() == Html.ViewData.Model.CompanyId)
{

<input type="text" name="companyCVR" placeholder="Indsæt CVR-nr."/>
}

}


and at the bottom of the page I have the submit button with the id above ("cvr") where I am trying to add two more forms to pass on to the controller (repFirstName and repLastName):

@if (User.Identity.GetUserId() == Html.ViewData.Model.CompanyId)
{
using (Html.BeginForm("SendMailAsACompany", "Contract", null, FormMethod.Post, new { id = "cvr" }))
{

<input type="text" name="repFirstName" placeholder="Indsæt fornavn" />
<input type="text" name="repLastName" placeholder="Indsæt lastnavn" />

}
<input type="button" value="Submit" onclick="$('#cvr').submit();" class="btn btn-success" />
}


However they will not pass on submit, only the first value (the CPR above). However if I have all three values at the start, they will pass successfully.

How can I have the input in both places and still be able to submit and pass the data to the controller? Do I need two separate forms/ids ?

Answer

Only one form is required, remove the second form declaration and associate element with form using form attribute which is defined at the bottom of page.

The form attribute is used to associate an input, select, or textarea element with a form (known as its form owner).

@if (User.Identity.GetUserId() == Html.ViewData.Model.CompanyId)
{
    <input type="text" name="repFirstName" placeholder="Indsæt fornavn" form="cvr"/>
    <input type="text" name="repLastName" placeholder="Indsæt lastnavn" form="cvr"/>
    <button form="cvr" class="btn btn-success">Submit</button>
}