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

Time:02-06

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 >
        <div >
            <h2 >Create Branch</h2>
            <hr/>
        </div>
        <div >
            <label asp-for="branch.BranchName">Branch Name</label>
            <input asp-for="branch.BranchName" />
            <span asp-validation-for="branch.BranchName" ></span>
        </div>
        <div >
            <label asp-for="branch.City">City</label>
            <input asp-for="branch.City" />
            <span asp-validation-for="branch.City" ></span>
        </div>
        <div >
           <div >
                    <div >
                        <label asp-for="branch.CompanyId">Company</label>
                    </div>
                    <div >
                        @Html.DropDownListFor(m => m.branch.CompanyId, Model.CompaniesList , "Select Order",
                       new { @class = "form-control" })
                        <span asp-validation-for="branch.CompanyId" ></span>
                    </div>
                </div>
     </div>
         <div >
                <input type="hidden" asp-for="branch.CreatedAt"  value="@DateTime.Now" />
            </div>
            <div >
                <input type="hidden" asp-for="branch.CreatedBy"  [email protected] />
            </div>
        <button type="submit"  style="width:200px">Add New Branch</button>
        <a asp-controller="Company" asp-action="Index"  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);
}

CodePudding user response:

One technique is to make it nullable:

public IEnumerable<SelectListItem>? CompaniesList { get; set; }
  •  Tags:  
  • Related