我有一个Controller操作,它接收2个URL参数,这些参数是数据模型的外键:
public ActionResult Create(SurveyResponseModel surveyresponsemodel, int MemberId, int ProgramId)
{
surveyresponsemodel.MemberId = MemberId;
surveyresponsemodel.ProgramId = ProgramId;
return View(surveyresponsemodel);
}
以下是数据模型:
public class SurveyResponseModel
{
[Key]
public int ResponseId { get; set; }
public int MemberId { get; set; }
public int ProgramId { get; set; }
// "If yes, what changes did you make? Mark all that apply."
[DisplayName("Did you make any changes in your practice, research, or administration activities as a result of participating in this CME activity?")]
public string CmeChanges { get; set; }
[DisplayName("Better patient follow-up")]
public bool PatientFollowUp { get; set; }
public virtual SurveyProgramModel SurveyProgramModel { get; set; }
public virtual PersonModel PersonModel { get; set; }
“SurveyProgramType”的数据模型
public class SurveyProgramModel
{
[Key]
public int ProgramId { get; set; }
public int ProgramYear { get; set; }
public int ProgramStatusId { get; set; }
public string ProgramTitle { get; set; }
public int ProgramTypeId { get; set; }
public virtual SurveyProgramTypeModel ProgramType { get; set; }
public virtual ProgramStatusModel ProgramStatusModel { get; set; }
}
我希望在我的视图中能够执行的操作是通过为ProgramTitle
传递的URL参数检索ProgramId
。所以视图看起来像:
<div class="editor-label">
@Model.SurveyProgramModel.ProgramTitle
</div>
但是,@ Model.SurveyProgramModel.ProgramTitle抛出异常,因为它为null。我想我的导航属性设置不正确。知道那是什么吗?
答案 0 :(得分:1)
您不应该将视图模型返回到视图吗?
public ActionResult Create(
SurveyResponseModel surveyresponsemodel) //, int MemberId, int ProgramId)
{
// MemberId and ProgramId arguments do not need to be defined
// They will be picked up my MVC model binder, since there are properties
// with the same name in SurveyResponseModel class
//surveyresponsemodel.MemberId = MemberId;
//surveyresponsemodel.ProgramId = ProgramId;
surveyresponsemodel.SurveyProgramModel = new SurveyProgramModel(); // new line
return View(surveyresponsemodel); // <- return your view model here
}
答案 1 :(得分:0)
未将模型传递给视图,您无法在视图中访问模型的属性。这就是错误的可能原因。
public ~ActionResult PassModel(DemoModel _model, int id)
{
// your code goes here....
return View(_model); // pass the model to view ..so you can work on your model
}