我试图通过我的控制器将ID从一个视图传递到另一个视图,但不知怎的,我不断收到错误,它无法转换为' int'到' Namespace.Modal.name'?
这是我的电子邮件模型中的代码:
public int emailID { get; set; }
[Display(Name = "Email address")]
[Required(ErrorMessage = "The email address is required")]
[DataType(DataType.EmailAddress)]
[EmailAddress]
public string emailadres { get; set; }
public string omschrijving { get; set; }
public bool verwijderd { get; set; }
public virtual Vrijwilligers vrijwilligerID { get; set; }
以下是我的控制器代码:
public ActionResult Create([Bind(Include = "emailID,emailadres,omschrijving,verwijderd,vrijwilligerID")] Email email)
{
if (ModelState.IsValid)
{
int id = int.Parse(HttpContext.Session["vrijwilligersID"].ToString());
email.vrijwilligerID = id;
email.verwijderd = false;
db.Emails.Add(email);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(email);// vrijwilligers details
}
错误来自这个特定部分:
int id = int.Parse(HttpContext.Session["vrijwilligersID"].ToString());
email.vrijwilligerID = id;
调试时我发现ID正在传递但不正确。
答案 0 :(得分:1)
由于@Equalsk指出vrijwilligerID
不是Int
,而是object
,您需要使用该ID从Vrijwilligers
获取项目,所以;
email.vrijwilligerID = db.Vrijwilligers.FirstOrDefault(x=> x.Id == id);
希望有所帮助,