I am sure this is quite straightforward but I am a bit stuck here. The routing defined for my app is just the default. I have the following controller defined.
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();
}
}
}
When I navigate to /Admin/EditDocument/1/
then the first action executes exactly as expected, rendering the following view:-
<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" />
}
On submitting this I get an error:-
No parameterless constructor defined for this object.
Other questions seemingly related questions MVC: No parameterless constructor defined for this object suggest that it is a to do with the IoC container not being set up properly, but surely the fact that the first action executes without a problem means that isn't the problem here?
Any help would be greatly appreciated.
Regards.
Simon
add to class DocumentEditViewModel default constructor
public DocumentEditViewModel (){}
The MVC framework is trying to create an instance of the DocumentViewModel class but it can't find a publicly accessible default constructor (that does not take any arguments). You can either define such a default constructor like @simplyDenis suggested or define a cusotm ModelBinder that can create the instance using your custom constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With