I have a form with a bunch of controls, but not everyone is required to fill in, so I get an error when I receive the form because some values are not present. I've tried to define default values on the function, but I think it's the [FromForm]
that is causing the error.
<table>
<tr>
<td> </td>
<td><input type="text" id="AddressLine1" name="AddressLine1" class="txt-antan address-line" onkeyup="verifyInput()" onchange="verifyInput()" /></td>
</tr>
<tr>
<td> </td>
<td><input type="text" id="AddressLine2" name="AddressLine2" class="txt-antan address-line" onkeyup="verifyInput()" onchange="verifyInput()" /></td>
</tr>
<tr>
<td> </td>
<td><input type="text" id="AddressLine3" name="AddressLine3" class="txt-antan address-line" onkeyup="verifyInput()" onchange="verifyInput()" value="-" /></td>
</tr>
<tr>
<td> </td>
<td><input type="text" id="AddressLine4" name="AddressLine4" class="txt-antan address-line" onkeyup="verifyInput()" onchange="verifyInput()" value="-" /></td>
</tr>
<tr>
<td> </td>
<td><input type="text" id="AddressLine5" name="AddressLine5" class="txt-antan address-line" onkeyup="verifyInput()" onchange="verifyInput()" placeholder="@_local["WordAddresss"]" /></td>
</tr>
</table>
AddressLine 3 to 5 are not required and may be empty.
[HttpPost("API/SetCartIdentity")]
public async Task<IActionResult> SetCartIdentityAsync([FromForm(Name = "AddressLine1")] string addressLine1, [FromForm(Name = "AddressLine2")] string addressLine2, [FromForm(Name = "AddressLine3")] string addressLine3, [FromForm(Name = "AddressLine4")] string addressLine4, [FromForm(Name = "AddressLine5")] string addressLine5 = "default value")
{
return RedirectToActionPermanent("Checkout", "Cart");
}
It will cause an error if any of the input's are empty.
I would suggest creating a class for your input model similar to this:
using System.ComponentModel.DataAnnotations;
namespace MySample
{
public class InputModel
{
[Required]
public string AddressLine1 { get; set; }
[Required]
public string AddressLine2 { get; set; }
public string AddressLine3 { get; set; }
public string AddressLine4 { get; set; }
public string AddressLine5 { get; set; } = "default value";
}
}
Then, your method signature would look like this:
[HttpPost("API/SetCartIdentity")]
public async Task<IActionResult> SetCartIdentityAsync(InputModel model)
{
return RedirectToActionPermanent("Checkout", "Cart");
}
You could then also review the form tag helpers available: https://docs.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms?view=aspnetcore-6.0#the-input-tag-helper
And the validation components here: https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/validation?view=aspnetcore-6.0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.