I have ASP MVC 4 project. I have problem that when I try to create new Survey the code in the controller also fail to bind the posted form data to the model.
The specific error is:
The parameter conversion from type 'System.String' to type 'DNASurvey.Models.Tenant' failed because no type converter can convert between these types. {System.InvalidOperationException}
Those are the models I have:
public class Tenant {
[Key]
public string TenantID { get; set; }
public string Name { get; set; }
public virtual ICollection<Survey> Surveys { get; set; }
}
public class Survey {
[Key]
public string SurveyID { get; set; }
[Required]
public virtual Tenant Tenant { get; set; }
[Required]
[StringLength(100, MinimumLength=5)]
public string Title { get; set; }
[Required]
public DateTime CreatedAt { get; set; }
[Required]
public uint CurrentRoundIndex { get; set; }
}
I also have SurveyController with this relavant code:
public ActionResult Create() {
AddPossibleTenants();
return View();
}
//
// POST: /Survey/Create
[HttpPost]
public ActionResult Create(Survey survey) {
if (ModelState.IsValid) {
survey.SurveyID = EncodeNameToSingleString(survey.Title);
db.Surveys.Add(survey);
db.SaveChanges();
return RedirectToAction("Index");
}
AddPossibleTenants();
return View(survey);
}
private void AddPossibleTenants() {
ViewBag.PossibleTenants = db.Tenants.ToList();
}
And this view for create:
@model DNASurvey.Models.Survey
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Survey</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Tenant)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.Tenant, new SelectList(ViewBag.PossibleTenants, "TenantID", "Name"))
@Html.ValidationMessageFor(model => model.Tenant)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.CreatedAt)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.CreatedAt)
@Html.ValidationMessageFor(model => model.CreatedAt)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}