简体   繁体   English

如何将数据从视图传递到控制器?

[英]How to passdata from View to Controller?

I have a ViewModel like that:我有一个这样的 ViewModel:

    public class JobApplication
    {
        [Key]
        public int Id{ get; set; }
        [Required]
        public DateTime CreatedOn { get; set; }

        [DataType(DataType.Date)]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyy-MM-dd}")]
        [Display(Name = "Edited on:")]
        public DateTime? EditedOn { get; set; }
        [DataType(DataType.Date)]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyy-MM-dd}")]
        [Display(Name = "Deleted on:")]
        public DateTime? DeletedOn { get; set; }


        public User Applicant { get; set; }

        public JobOffer JobOffer { get; set; }

        public ApplicationStatus ApplicationStatus { get; set; }

        public string CvHandle { get; set; }
        public string AdditionalInformation { get; set; }
    }

The fields JobOffer and Applicant make it to the view correctly, so I can access them. JobOfferApplicant字段正确显示在视图中,因此我可以访问它们。 However, I want to then pass them back to the [HttpPost] method in the Controller.但是,我想然后将它们传递回控制器中的[HttpPost]方法。 So far I've tried using Hidden and HiddenFor :到目前为止,我已经尝试使用HiddenHiddenFor

@Html.Hidden("JobOffer", Model.JobOffer)
@Html.Hidden("Applicant", Model.Applicant)
@Html.HiddenFor(x => x.Applicant)
@Html.HiddenFor(x => x.JobOffer)

But those don't work - all other values are mapped correctly when they make it to the Controller's method, but those are still null .但是那些不起作用 - 所有其他值在它们进入 Controller 的方法时都被正确映射,但它们仍然是null How can I pass those values correctly back to the Controller with Post?如何使用 Post 将这些值正确传递回控制器?

It is better to store these values on server side, but if you indeed want to pass them through, you can use this format for each property of these objects:最好将这些值存储在服务器端,但如果您确实想传递它们,则可以对这些对象的每个属性使用以下格式:

@Html.HiddenFor(x => x.Applicant.Field1)
@Html.HiddenFor(x => x.Applicant.Field2)
@Html.HiddenFor(x => x.JobOffer.Field1)
@Html.HiddenFor(x => x.JobOffer.Field2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM