1

I have a model with 2 fields and both are non required(no [Required] tag is used).

On the razor page I have unobtrusive and jquery validation js files included. When I do not fill any value and post the form I get an error(client side) that ask for the last field in my form is required.

I have searched but have not found similar issue, as there is no required tag in model/viewmodel then why this is required on client side.

[Update 1 : code added]

Model:

public class AppUser: IdentityUser
{
public string Name { get; set; }
public int Deposit { get; set; }
}

View:

<form method="post">
    <div class="form-group">
        <label asp-for="@Model.AppUser.Deposit" class="control-label"></label>
        <input asp-for="@Model.AppUser.Deposit" type="text" class="form-control" />
        <span asp-validation-for="@Model.AppUser.Deposit" class="text-danger"></span>
    </div>

    <div class="form-group">
        <label asp-for="@Model.AppUser.Email" class="control-label"></label>
        <input asp-for="@Model.AppUser.Email" type="text" class="form-control" />
        <span asp-validation-for="@Model.AppUser.Email" class="text-danger"></span>
    </div>
</form>

Controller:

public class SomeModel : PageModel
{
private readonly ApplicationDbContext _context;
private readonly UserManager<AppUser> _userManager;

[BindProperty]
public AppUser AppUser { get; set; }

public SomeModel(ApplicationDbContext context, UserManager<AppUser> userManager)
{
    _context = context;
    _userManager = userManager;
}

public async Task<IActionResult> OnGetAsync()
{
    //..some action
    return Page();
}

public async Task<IActionResult> OnPostAsync()
{
    //..some action
    return Page();
}
}
user614946
  • 599
  • 5
  • 10
  • 27
  • The question is not clear to me, but if you want some field to be not reqired just don't put reqired attribute in the model.Also it will be better if you show some code. – mybirthname Sep 02 '18 at 08:53
  • @mybirthname I have added sample code.. issue is that "Deposit" field is required in client side javascript and I am not able to find out. – user614946 Sep 02 '18 at 16:18
  • @user614946 For `Deposit`, its type is `int` which is default non-null type, its default value is `0`, if you want to make it required, change it to `[Required]public int? Deposit { get; set; }` – Edward Sep 03 '18 at 02:01
  • 1
    so if type like int and double are then unobtrusive will make it default required in UI because they must have a non zero value? I think its a bit faulty as this field is not required and null should be allowed by default. – user614946 Sep 03 '18 at 16:00
  • An `int` can never have a `null` value? - it cannot so its required by default –  Oct 11 '18 at 09:40

1 Answers1

1

By default non-nullable types like int, double, byte, ... are required if you want them to be optional you have to use nullable type e.g. int?

NewDeveloper
  • 85
  • 3
  • 9