Casey Crookston
Casey Crookston

Reputation: 13945

Persist model field from GET to POST

In the controller's GET method, I pick up a parameter (id) from the query string and assign it to a property in the model, which then gets sent to the view.

The view contains a form in which the user will supply the rest of the values for this model. When the model then gets sent back to the POST method, I need that original parameter (id) back again. But I'm not sure how to persist it. In the POST method, the id field is coming back blank. Is there a better way to do this?

    // GET: CreateInsured
    [Route("Home/CreateInsured/{id}")]
    public ActionResult CreateInsured(int id)
    {
        Insured insured = new Insured();
        insured.PolicyId = id;
        return View(insured);
    }

    // POST: CreateInsured
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult CreateInsured(Insured insured)
    {
       //insured.PolicyId is empty
    }

Upvotes: 0

Views: 91

Answers (1)

Pedro Benevides
Pedro Benevides

Reputation: 1980

You should put this Id into a Hidden field, like this:

@Html.HiddenFor(m => m.PolicyId)

And this field should be into your form.

Upvotes: 2

Related Questions