简体   繁体   中英

Error “No parameterless constructor defined for this object.” with SelectList from ViewModel

In my viewmodel I made two SelectList properties with names of cities coming from an external database.

ViewModel

namespace Treinreizen.Models.ViewModels
{
    public class ReizenViewModel
    {
        public SelectList VanStad { get; set; }

        public SelectList NaarStad { get; set; }
    }
}

In my controller I use one GET method "Registratie" where the user can select cities and one POST method to post this cities. The problem is that I get the error

"No parameterless constructor defined for this object."

when I try to post my form. In the Stack Trace it says:

"[MissingMethodException: No parameterless constructor defined for this object.]" and "[MissingMethodException: No parameterless constructor defined for this object. Object type 'System.Web.Mvc.SelectList'.]"

Controller

        // GET: Hotels/Registratie
        public ActionResult Registratie()
        {
            stedenServices = new StedenServices();
            ReizenViewModel registratieviewmodel = new ReizenViewModel();
            registratieviewmodel.VanStad = new SelectList(stedenServices.All(), "StadID", "Stad");
            registratieviewmodel.NaarStad = new SelectList(stedenServices.All(), "StadID", "Stad");
            return View(registratieviewmodel);
        }

        // POST: Hotels/Registratie
        [HttpPost]
        public ActionResult Registratie(ReizenViewModel registratie)
        {
            if (ModelState.IsValid)
            {
                return RedirectToAction("Index");
            }
            return View(registratie);
        }

View

    <div class="form-group">
        @Html.LabelFor(model => model.VanStad, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(m => m.VanStad, Model.VanStad, "--Selecteer Stad--")
            @Html.ValidationMessageFor(model => model.VanStad, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.NaarStad, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(m => m.NaarStad, Model.NaarStad, "--Selecteer Stad--")
            @Html.ValidationMessageFor(model => model.NaarStad, "", new { @class = "text-danger" })
        </div>
    </div>

只需向ReizenViewModel添加一个无参数的构造函数即可:

public ReizenViewModel(){}

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