0

我有一个控制器操作接收 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通过为ProgramId. 所以视图看起来像:

<div class="editor-label">
            @Model.SurveyProgramModel.ProgramTitle
        </div>

但是,@Model.SurveyProgramModel.ProgramTitle 抛出异常,因为它为空。我在想我的导航属性设置不正确。知道那是什么吗?

4

2 回答 2

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
} 
于 2012-07-02T15:35:48.667 回答
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 
              }
于 2012-07-02T15:46:22.840 回答