简体   繁体   中英

The parameter conversion from type 'System.String' to type 'System.Web.Mvc.SelectListItem' failed

I am getting error in my MVC application. I have page where some textfields and one dropdown is there. Data is loading correctly to that page when When I submit the page, ModelState is returning error that

The parameter conversion from type 'System.String' to type 'System.Web.Mvc.SelectListItem' failed because no type converter can convert between these types.

Controller methods

public ActionResult Edit(string id)
{
    ....
    EditUserViewModel vm = new EditUserViewModel()
    .... // populate the view model including its SelectList properties
    return View(vm);
}

The data is correctly populated as per the following image

在此处输入图片说明

But when Its submitted back to controller, model state is invalid and gives error.

And view model

public class EditUserViewModel
{
        public string UserID { get; set; }
        public string SelectedRoleName { get; set; }
        public IEnumerable<SelectListItem> Roles { get; set; }
        public string SelectedCompanyID { get; set; }
        public IEnumerable<SelectListItem> Companies { get; set; }
        ....
    }

View is as below

....
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.HiddenFor(model => model.UserID)
    @Html.DropDownListFor(model => model.SelectedRoleName, Model.Roles)
    @Html.DropDownListFor(model => model.SelectedCompanyID, Model.Companies, 
    @Html.HiddenFor(model => model.Companies)
    ....

    <input type="submit" value="Save" class="btn btn-default" />
}

The error occurs because of the following line of code in the view

@Html.HiddenFor(model => model.Companies)

If you inspect the html it is generating, it will be

<input ... name="Companies" value="System.Collections.Generic.List`1[System.Web.Mvc.SelectListItem]" />`

When you submit the form, The DefaultModelBinder attempts to bind property Companies to that value and fails (you cannot bind a property which is IEnumerable<SelectListItem> to a string ).

Remove that line of code. And if you need to return the view because ModelState is invalid for other reasons, then re-populate the SelectLists before you return the view.

I have resolved this error by removing {get; set;} from the SelectListItem property

public IEnumerable<SelectListItem> Companies { get; set; }

replaced with

public IEnumerable<SelectListItem> Companies

change input name .

$(document).ready(function () {
$('#Companies').attr('name', ' ');
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM