简体   繁体   中英

Getting a value to persist from one form to another in the same view

My view has two Forms...

@using (Html.BeginForm("Upload", "CSV", 
null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{

   --file picker--

    <div class="form-group">
        <input type="submit" value="Upload" class="btn btn-default" />
    </div>

}

@using (Html.BeginForm("Add", "CSV", 
null, FormMethod.Post, new { enctype   = "multipart/form-data" }))

{

   --- other functionality--

     <div class="form-group">
     <input type="submit" value="Add" id="ShortURL" class="btn btn-default" />
     </div>

}

This view is linked to a model with an ID field. By the time I get to this view I am passing along the ID from another view which I need to perform the "Add" method. And if I do the "Add" first it works fine.
However, if I do the "Upload" first then I lose the ID when it gets back to the controller. How can I store the ID after going to the Upload method first and then the Add method?

Here are the relevant controller methods...

[HttpPost]
    public ActionResult Upload(HttpPostedFileBase upload)
    {
        if (ModelState.IsValid)
        {
            if (TempData["Model"] != null)
            {
                var data = TempData["Model"] as CSV;
                CSV UploadData = data;
                UploadData.ID = UploadData.Upload(upload, data.ID);
                return View("CSV", UploadData);
            }
        }
       return View("CSV");
   }


    public ActionResult CSV(CSV Model)
    {
        TempData["Model"] = Model;
        return View("CSV",Model);
    }

   [HttpPost]
    public ActionResult Add(CSV Model)
    {
      //need to use the ID field in here
     }

You can try to use inside the controller

TempData.Peek("Model")

instead of

TempData["Model"]

TempData marks the data associated the key to be deleted after one call/usage. By using the peek method you are able to view the value associated with the key without deleting it. Because of that behavior, which deletes itself after one time use so you have to either peek or keep to persist the data over one usage.

Another way would be

TempData["model"]
// some code
TempData.Keep("model")

More detailed and clearer explanation: TempData keep() vs peek()

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