C# ASP.NET Core Cannot bind to a model of type 'Microsoft.AspNetCore.Http.FormCollection'
Asked Answered
P

2

6

I am getting the following error An unhandled exception occurred while processing the request. InvalidOperationException: The 'Microsoft.AspNetCore.Mvc.ModelBinding.Binders.FormCollectionModelBinder' cannot bind to a model of type 'Microsoft.AspNetCore.Http.FormCollection'. Change the model type to 'Microsoft.AspNetCore.Http.IFormCollection' instead.

This is when I use the following code:

[ValidateAntiForgeryToken]
[HttpPost]
public IActionResult Index(Test test, FormCollection formCollection)
{        
    var feesAmountArray = new List<string>();

    foreach (var item in formCollection.Keys.Where(k => k.StartsWith("FeesAmount-")))
    {
        feesAmountArray.Add(formCollection[item].ToString().TrimEnd(','));
    }

    var feesAmount = string.Join(",", feesAmountArray);

    if (ModelState.IsValid)
    {
    }

    return View(test);
}

Within the model Test I am using a [Decimal] attribute which is used in conjunction with a ModelBinder, but I am not wanting to bind to the form in anyway, I just want to bind to the model, so I am a little confused as to why this message is presenting itself.

The code relating to the ModelBinder can be found at:

C# ASP.NET Core ModelBinder not Updating Model

Any help would be much appreciated :-)

Preengage answered 6/9, 2017 at 8:43 Comment(6)
What do you expect to go into the formCollection value if you don't want it to be part of model-binding?Osteomalacia
The main form is bound to the Test model but the form can include some dynamic fields created by jQuery, so I need primarily to validate the base Test model and in addition check for dynamic fields generated which do not exist in the Test model.Preengage
I've added extra code to address the need for FormCollection.Preengage
Ok, next question: Why can't you heed the advice of the error and just use IFormCollection instead of FormCollection?Osteomalacia
Not sure if it justified a mark down. The reason for asking the question is that I didn't understand the error. I was only using model binding for certain attributes in the Test model, I wasn't using any model binding for the FormCollection, hence the confusion.Preengage
I didn't down vote (I generally don't), but I expect anyone that does would do so due to the fact that the solution was clear in the error message you provided.Osteomalacia
P
11

Two options:

  1. Change your parameter to be IFormCollection
  2. Remove it and instead access it through HttpContext.Form
Pontone answered 6/9, 2017 at 9:54 Comment(1)
How do I get the values in the Post method and save?Malaria
K
0

Use like below and import using Microsoft.AspNetCore.Http; namespace.

 [HttpPost]
        public ActionResult Create(IFormCollection foFormCollection)
        {
            try
            {
                UserDataContext DBContext = new UserDataContext();
                Users Users = new Users();

                Users.EmpName = foFormCollection["EmpName"].ToString();
                Users.UserPassword = foFormCollection["UserPassword"].ToString();
                Users.flgIsActive = string.IsNullOrEmpty(foFormCollection["ActiveStatus"]) ? false : true;
                Users.EmployeeId = foFormCollection["EmployeeId"].ToString() == "0" ? 0 : Convert.ToInt64(foFormCollection["EmployeeId"]);

                Int64 Success = DBContext.addEditUser(Users)
                return RedirectToAction("pagename");
            }
            catch
            {
                return RedirectToAction("pagename");
            }
        }
Kilometer answered 17/5, 2021 at 6:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.