我有 ASP MVC 4 项目。我有一个问题,当我尝试创建新的调查时,控制器中的代码也无法将发布的表单数据绑定到模型。
具体错误是:
从类型“System.String”到类型“DNASurvey.Models.Tenant”的参数转换失败,因为没有类型转换器可以在这些类型之间进行转换。{System.InvalidOperationException}
这些是我拥有的模型:
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; }
}
我也有带有此相关代码的 SurveyController:
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();
}
这个视图用于创建:
@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")
}