1

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)")

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

I don't want to change any of the Tenant fields with this editor, just select between tenants. I would think setting the Tenant field on DocumentViewModel to a nullable type would make sense, except it's already nullable.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.