I have a hidden field in my view and I'm trying to add a value to it in the validateForm() JavaScript function. I see the value is getting changed on the output window. However, Model that is being passed to controller as a parameter receiving it as Null.
Here is the code that I have tried
Cshtml:
@using (Html.BeginForm("ViewAch", "AchNew", FormMethod.Post, new { enctype = "multipart/form-data", id = "CreateACHForm", onsubmit = "validateForm()" }))
{
<label>First Name <span>*</span></label>
@Html.TextBoxFor(m => m.FirstName, new { maxlength = 19, @class = "input-required form-control form-control-sm", id = "fname" })
@Html.ValidationMessageFor(m => m.FirstName, "")
<label>First Name <span>*</span></label>
@Html.TextBoxFor(m => m.FirstName, new { maxlength = 19, @class = "input-required form-control form-control-sm", id = "fname" })
@Html.ValidationMessageFor(m => m.FirstName, "")
@Html.AntiForgeryToken();
@Html.HiddenFor(m => m.TokenizedPayloadNonce);
<input type="submit" value="SignUp" class="btn btn-primary btn-lg btn-block" />
}
JavaScript:
function validateForm() {
var NewToken = callExternalSytem(); // retrieving value from the external system
document.getElementById('TokenizedPayloadNonce').value = NewToken;
}
Here is how I'm reading it from the controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ViewAch(AchProfile achProfile)
{
var token = achProfile.TokenizedPayloadNonce;
}
I am able to access the other field values but not the ones that I updated in validateForm(). Is there something that I'm missing?
Regarding your case, you can use this method to send the updated value to your Controller
:
We first change the type of your SignUp
from submit
to button
and bind the validateForm
to its onclick
event :
@using (Html.BeginForm("ViewAch", "AchNew", FormMethod.Post, new { enctype = "multipart/form-data", id = "CreateACHForm"}))
{
<label>First Name <span>*</span></label>
@Html.TextBoxFor(m => m.FirstName, new { maxlength = 19, @class = "input-required form-control form-control-sm", id = "fname" })
@Html.ValidationMessageFor(m => m.FirstName, "")
<label>First Name <span>*</span></label>
@Html.TextBoxFor(m => m.FirstName, new { maxlength = 19, @class = "input-required form-control form-control-sm", id = "fname" })
@Html.ValidationMessageFor(m => m.FirstName, "")
@Html.AntiForgeryToken();
<input type="hidden" id="myTokenizedPayloadNonce" name="TokenizedPayloadNonce"/>
<input type="button" value="SignUp" class="btn btn-primary btn-lg btn-block" onclick="validateForm()" />
}
Once the binding is done, then we use Javascript
to submit your form to the Controller
. This will bind the updated value that you required to your Model
:
function validateForm() {
var NewToken = callExternalSytem(); // retrieving value from the external system
document.getElementById('myTokenizedPayloadNonce').value = NewToken;
document.getElementById('CreateACHForm').submit();
}