user1269310
user1269310

Reputation: 342

Why won't my Edit screen validation allow null?

I added a field to a view model for a Document that should allow the user to associate it with a Tenant. It works fine if the user does assign a tenant, but if they select the null option from the dropdown, then the validation tells me that "The ItemID field is required.", where ItemID is a field on TenantViewModel.

It occurs to me that perhaps I'm using editor templates wrong - I'm trying to select from a list of tenants, not edit a tenant. If that's wrong, let me know, and maybe suggest a better way to get the dropdown.

namespace TenantPortal.Models
{
    public class DocumentViewModel
    {
        ...

        [UIHint("SelectTenant")]
        public TenantViewModel Tenant { get; set; }
     }

    public class TenantViewModel
    {
        private Tenant _ten = null;

        public int ItemID { get; set; }

        public string Display_Name { get; set; }

        public string Legal_Name { get; set; }

        ...
    }
}

Editor Template: SelectTenant.cshtml

@using CMS.DocumentEngine.Types.Tenantportal
@using TenantPortal.Models
@model TenantViewModel

@{ 
    Layout = null;

    var opts = new SelectList(TenantProvider.GetTenants(), "ItemID", "Display_Name");
}

@Html.DropDownListFor(model => model.ItemID, opts, "(none)")

Upvotes: 1

Views: 701

Answers (3)

user1269310
user1269310

Reputation: 342

I ended up adding another property to my document view model named TenantID, having it communicate with the Tenant property behind-the-scenes, and creating SelectLists for TenantID dropdowns on both Create and Edit views. It's less elegant than I would like, but it works.

Upvotes: 0

David
David

Reputation: 34563

Your ItemID field is an int so it does not allow null values so the model validation fails. Try changing it to int? (a nullable int). If a value is not set in the form, then the value will be null, but if a value is selected, the ItemID will be the selected value.

Upvotes: 1

Derviş Kayımbaşıoğlu
Derviş Kayımbaşıoğlu

Reputation: 30565

If you use data annotations you can add validation to your model.

See my example below:

public class TenantViewModel
{
    private Tenant _ten = null;

    [Required]
    public int ItemID { get; set; }

    [Required]
    [MaxLength(30)]
    public string Display_Name { get; set; }

    public string Legal_Name { get; set; }

    ...
}

For further information about data annotations check this

Also, on your code/controller-action side, you need to use ModelState.IsValid check in order to verify whether your model is valid or not

Upvotes: 1

Related Questions