简体   繁体   中英

How do I retain parameter values from the GET ActionResult to re-use in the POST ActionResult?

I am sending parameters to the GET ActionResult like this:

public ActionResult MyFormLetter(string studentName, string teacherName, string courseName, string appointmentDate)
{    
    // Do stuff here;
}

After clicking on a form button that calls the POST ActionResult, those values are out of scope. Ho can I retain the values in the GET ActionResult to reuse in the Post ActionResult?

Thanks for any help!

Do you have a strongly typed view? your view should have a model that holds the values from the Get right (studentname, teachername...etc)

Then on the Post Action, it can accept a parameter of the same class, the model will automatically get the values from the form variables (it will automatically matches values to properties of the model whenever possible).

You should be using a ViewModel for this, as well as a strongly-typed View. Something like this would work:

public class StudentInformation
{
    public string StudentName { get; set; }
    public string TeacherName { get; set; }
    public string CourseName { get; set; }
    public string AppointmentDate { get; set; }
}

Your Action methods would look like this:

public ActionResult MyFormLetter()
{
    return View();
}

[HttpPost]
public ActionResult MyFormLetter(StudentInformation studentInformation)
{
    // do what you like with the data passed through submitting the form

    // you will have access to the form data like this:
    //     to get student's name: studentInformation.StudentName
    //     to get teacher's name: studentInformation.TeacherName
    //     to get course's name: studentInformation.CourseName
    //     to get appointment date string: studentInformation.AppointmentDate
}

And a little View code:

@model StudentInformation


@using(Html.BeginForm())
{
    @Html.TextBoxFor(m => m.StudentName)
    @Html.TextBoxFor(m => m.TeacherName)
    @Html.TextBoxFor(m => m.CourseName)
    @Html.TextBoxFor(m => m.AppointmentDate)

    <input type="submit" value="Submit Form" />
}

When you reach the Action method from the POST of the submit, you will then have access to all of that data that was input into your form view.

Disclaimer: The View code just shows the necessary elements to show how data is saved in the model for Model Binding.

您可以将值放在隐藏字段中,以便将它们发布到POST操作中,然后可以将它们捆绑在POST方法的ActionResult中。

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