I have a contact Razor page backed by a ViewModel called ContactViewModel
. The html generated is below.
<form method="post">
<div class="form-group">
<input placeholder="First Name" class="form-control" type="text" id="ContactViewModel_FirstName" name="ContactViewModel.FirstName" value="" />
</div>
<div class="form-group">
<input placeholder="Last Name" class="form-control" type="text" id="ContactViewModel_LastName" name="ContactViewModel.LastName" value="" />
</div>
<input type="submit" value="SUBMIT" class="btn btn-default" />
</form>
I have another Razor Page with a form backed by ShippingAddressViewModel
.
<form method="post">
<div class="form-group">
<input placeholder="First Name" class="form-control" type="text" id="ShippingAddressViewModel_FirstName" name="ShippingAddressViewModel.FirstName" value="" />
</div>
<div class="form-group">
<input placeholder="Last Name" class="form-control" type="text" id="ShippingAddressViewModel_LastName" name="ShippingAddressViewModel.LastName" value="" />
</div>
<div class="form-group">
<input placeholder="Zip Code" class="form-control" type="text" id="ShippingAddressViewModel_ZipCode" name="ShippingAddressViewModel.ZipCode" value="" />
</div>
<input type="submit" value="SUBMIT" class="btn btn-default" />
</form>
I want to apply JS client validation to the FirstName
and LastName
. Since the name
and id
of the controls are different, I have to create two JavaScript methods to target the controls.
Is there a way in Razor Pages to back the page with different view models but the id
and name
are the same?
This problem is caused because you have an object. You can create two different variables in your PageModel.
[BindProperty]
public string FirstName { get; set; }
[BindProperty]
public string LastName { get; set; }
Now you your view can have the following code:
<input asp-for="FirstName" />
<input asp-for="LastName" />
This will have as a result to have the following html:
<input type="text" id="FirstName" name="FirstName" value="" />
<input type="text" id="LastName" name="LastName" value="" />
I hope it helps.