Reputation: 1150
I'm getting a 'No parameterless constructor defined for this object' exception and the culprit is a @Html.Action inside my view. I just figure out why this is happening. Any help would be greatly appreciated.
My Controller
public class AsyncController : Controller
{
public ActionResult Jobs()
{
var jobViewModel = new JobViewModel("Junior Accountant", Sector.Accountancy, DateTime.Now, "Enterprise Banking");
return View(jobViewModel);
}
public ActionResult MoreJobs(JobViewModel model)
{
var viewModel = new MiniJobsView(model);
return PartialView("_Rand.cshtml", viewModel);
}
}
Jobs View
@model SampleAsyncPartialViews.ViewModels.JobViewModel
@{
ViewBag.Title = "Jobs";
}
<h2>@Model.Title</h2>
<h3>@Model.CompanyName</h3>
<h3>@Model.Sector</h3>
<h3>@Model.StartDate</h3>
@Html.Action("MoreJobs", Model);
_Rand Partial View
@model SampleAsyncPartialViews.ViewModels.MiniJobsView
<div>
<h1>@Model.Title</h1>
</div>
JobViewModel
namespace SampleAsyncPartialViews.ViewModels
{
public class JobViewModel
{
public JobViewModel(string title, Sector sector, DateTime startDate, string companyName)
{
Title = title;
Sector = sector;
StartDate = startDate;
CompanyName = companyName;
}
public string Title { get; set; }
public Sector Sector { get; set; }
public DateTime StartDate { get; set; }
public string CompanyName { get; set; }
}
public enum Sector
{
Accountancy,
IT,
Marketing,
Sales
}
}
MiniJobsView
namespace SampleAsyncPartialViews.ViewModels
{
public class MiniJobsView
{
public MiniJobsView(JobViewModel model)
{
Title = model.Title;
StartDate = model.StartDate;
}
public string Title { get; set; }
public DateTime StartDate { get; set; }
}
}
I understand the exception, I just don't understand why @Html.Action would have to generate a new instance of JobViewModel, when i'm already passing the model.
Upvotes: 1
Views: 790
Reputation: 2747
The Html.Action
method wants the data like a object with route values.
// Correct:
@Html.Action("MoreJobs", new { model = Model});
// Wrong:
@Html.Action("MoreJobs", Model);
Upvotes: 0
Reputation: 1166
Actually you can't bind model using @Html.Action("MoreJobs", Model);
in your controller.
Try @Html.Partial("MoreJobs", new MiniJobsView(Model))
what CodeNotFound Said.
Upvotes: 0
Reputation: 23200
I think you need to render your partial view into your view. There is no overload for Html.Action that take your model as a parameter. The solution for doing what you want is to use Html.Partial methods like this :
@Html.Partial("MoreJobs", new MiniJobsView(Model))
Upvotes: 1