In an action, can I access different form element value?
For example I have 3 forms, first form contains common element.
<form id="commonSurname">
<input type="text" id="surname" name="surname" />
</form>
<form id="person1" asp-action="getPerson1" method="post">
<input type="text" id="name1" name="name1" />
<input type="submit" id="get1" name="get1" value="get1" />
</form>
<form id="person2" asp-action="getPerson2" method="post">
<input type="text" id="name2" name="name2" />
<input type="submit" id="get2" name="get2" value="get2" />
</form>
Controller;
public IActionResult getPerson1(string name1, string surname)
{
//I want use name1 and surname but surname is null
}
public IActionResult getPerson2(string name2, string surname)
{
//I want use name2 and surname but surname is null
}
2
Answers
A hidden field can be included in each form to store the value of surname. This ensures that every form submission sends the surname and you can update th value with js. Here is example for getPerson1 method
You can try this up, cheers
To access the form element value, we need the submission form contains the element which name is same with the parameter name and contains the value.
So, as Harun said, you can add a hidden field in each form to store the value of surname or use JS to add the form data before send request to action method.
Besides, I think you can also try to use one form to enter the value, then set the
asp-action
attribute on the submit button, so that you can also submit the form to different action.Code like this:
Controller:
Then, the result as below:
click get1:
click get2: