简体   繁体   English

获取值以在同一视图中从一种形式持久化到另一种形式

[英]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. 该视图链接到带有ID字段的模型。 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. 到该视图时,我从另一个视图传递ID,我需要执行“添加”方法。 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. 但是,如果我先执行“上传”,那么当它返回到控制器时,我会丢失ID。 How can I store the ID after going to the Upload method first and then the Add method? 先进入Upload方法然后再进入Add方法后,如何存储ID?

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. TempData标记与一次呼叫/使用后要删除的密钥相关的数据。 By using the peek method you are able to view the value associated with the key without deleting it. 通过使用peek方法,您可以查看与键关联的值,而无需删除它。 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() 更详细,更清晰的解释: TempData keep()vs peek()

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

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