简体   繁体   中英

How to passdata from View to Controller?

I have a ViewModel like that:

    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. However, I want to then pass them back to the [HttpPost] method in the Controller. So far I've tried using Hidden and HiddenFor :

@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 . How can I pass those values correctly back to the Controller with 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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