Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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" value=@ViewBag.userName />
            </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);
}

>Solution :

One technique is to make it nullable:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading