没有为此对象定义的无参数构造函数.在ASP.NET MVC控制器中

bay*_*ezy 10 asp.net-mvc

我相信这很简单,但我有点卡在这里.为我的应用程序定义的路由只是默认路由.我定义了以下控制器.

namespace Baynes.Wedding.Web.Controllers
{
    public class AdminController : Controller
    {
        private readonly IAuthProvider _authProvider;
        private readonly IDocumentRepository _documentRepository;

        public AdminController(IAuthProvider authProvider, IDocumentRepository documentRepository)
        {
            _authProvider = authProvider;
            _documentRepository = documentRepository;
        }

        public ViewResult EditDocument(int id)
        {
            var document = _documentRepository.Select(id);

            return View(new DocumentEditViewModel(document));
        }

        [HttpPost]
        public ActionResult EditDocument(DocumentEditViewModel model)
        {
            if (ModelState.IsValid)
            {
                _documentRepository.Update(model.ToDocument());
                return RedirectToAction("ListDocuments");
            }

            return View();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我导航到/Admin/EditDocument/1/第一个动作完全按预期执行时,呈现以下视图: -

<h2>@ViewBag.Title</h2>
@using (Html.BeginForm("EditDocument", "Admin", FormMethod.Post)) {
    @Html.ValidationSummary(true)
    @Html.HiddenFor(m => Model.Id)
    <div>
        @Html.LabelFor(m => Model.Title)
    </div>
    <div>
        @Html.TextBoxFor(m => Model.Title)
    </div>
    <div>
        @Html.LabelFor(m => Model.Body)
    </div>
    <div>
        @Html.TextAreaFor(m => Model.Body)
    </div>
    <div>
        @Html.LabelFor(m => Model.Url)
    </div>
    <div>
        @Html.TextBoxFor(m => Model.Url)
    </div>

    <input type="submit" value="Edit" />
}
Run Code Online (Sandbox Code Playgroud)

提交这个我收到一个错误: -

No parameterless constructor defined for this object.其他问题看似相关的问题MVC:没有为此对象定义的无参数构造函数表明它与IoC容器没有正确设置有关,但肯定是第一个操作执行没有问题的事实意味着这不是问题这里?

任何帮助将不胜感激.

问候.

西蒙

Med*_*tor 15

添加到类DocumentEditViewModel默认构造函数

public DocumentEditViewModel (){}
Run Code Online (Sandbox Code Playgroud)


JTM*_*Mon 5

MVC框架正在尝试创建DocumentViewModel类的实例,但它找不到可公开访问的默认构造函数(不带任何参数).您可以定义像@simplyDenis建议的默认构造函数,也可以定义可以使用自定义构造函数创建实例的cusotm ModelBinder.