Kobi
Kobi

Reputation: 145

ModelState Invalid on form submit - IEnumerable<SelectListItem> is required

I have a form that adds a branch, the form has a drop down to select the company name. I created a viewModel that has the SelectListItem of the companies and the Branch Model When submit a form, modelState.IsValid equals to false. reason for that is because CompaniesList is required. any idea why is it required? how can i overcome this?

Branch model:

public class Branch
    {
        public int Id { get; set; }
        public int CompanyId { get; set; }
        [MaxLength(50)]
        public string? City { get; set; }
        [MaxLength(50)]
        public string? BranchName { get; set; }
        public DateTime CreatedAt { get; set; }
        [MaxLength(100)]
        public string? CreatedBy { get; set; }
    }

ViewModel:

public class BranchVM
{
    public Branch branch { get; set; }
    [AllowNull]
    public IEnumerable<SelectListItem> CompaniesList { get; set; }
}

Create.cshtml:

@model Click2Lock.Models.BranchVM

<form method="post"  enctype="multipart/form-data">
    <div class="border p-3 mt-4">
        <div class="row pb-2">
            <h2 class="text-primary">Create Branch</h2>
            <hr/>
        </div>
        <div class="col-8">
            <label asp-for="branch.BranchName">Branch Name</label>
            <input asp-for="branch.BranchName" class="form-control"/>
            <span asp-validation-for="branch.BranchName" class="text-danger"></span>
        </div>
        <div class="col-8">
            <label asp-for="branch.City">City</label>
            <input asp-for="branch.City" class="form-control"/>
            <span asp-validation-for="branch.City" class="text-danger"></span>
        </div>
        <div class="col-8 pb-4">
           <div class="form-group row">
                    <div class="col-4">
                        <label asp-for="branch.CompanyId">Company</label>
                    </div>
                    <div class="col-8">
                        @Html.DropDownListFor(m => m.branch.CompanyId, Model.CompaniesList , "Select Order",
                       new { @class = "form-control" })
                        <span asp-validation-for="branch.CompanyId" class="text-danger"></span>
                    </div>
                </div>
     </div>
         <div class="col-8">
                <input type="hidden" asp-for="branch.CreatedAt" class="form-control" value="@DateTime.Now" />
            </div>
            <div class="col-8">
                <input type="hidden" asp-for="branch.CreatedBy" class="form-control" [email protected] />
            </div>
        <button type="submit" class="btn btn-primary" style="width:200px">Add New Branch</button>
        <a asp-controller="Company" asp-action="Index" class="btn btn-secondary" style="width:150px">
            Back To List
        </a>

    </div>
</form>

create on Controller :

public IActionResult Create()
{
    ViewBag.userName = (_unitOfWork.ApplicationUser.GetAll().
       Where(q => q.UserName == User.Identity.Name).Select(q => q.FullName)).FirstOrDefault();

    BranchVM branchVM = new BranchVM()
    {
        branch = new Branch(),
        CompaniesList = _unitOfWork.Company.GetAll().OrderBy(a=>a.CompanyName).
        Select(i => new SelectListItem
        {
            Text = i.CompanyName,
            Value = i.Id.ToString()
        })
    };
    return View(branchVM);
}
//POST
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(BranchVM branchVM)
{
    ViewBag.msgCreate = 0;
    ViewBag.msgGeneralException = 0;

    if (ModelState.IsValid)
    {
        try
        {
            _unitOfWork.Branch.Add(branchVM.branch);
            _unitOfWork.Save();
            ViewBag.msgCreate = 1;
            return View(branchVM);
        }
        catch (Exception ex)
        {
            ViewBag.msgGeneralException = 1;
            return View(branchVM);
        }
        
    }
    ViewBag.msgGeneralException = 1;
    return View(branchVM);
}

Upvotes: 2

Views: 447

Answers (1)

beautifulcoder
beautifulcoder

Reputation: 11330

One technique is to make it nullable:

public IEnumerable<SelectListItem>? CompaniesList { get; set; }

Upvotes: 4

Related Questions