Scorpio
Scorpio

Reputation: 1171

Model on the razor view is not getting updated on form submit

  public ActionResult Index(int id, string name)
  {
        var model = new ITViewModel
        {
           Packages = _Repository.GetDeployedPackages(id)
        };
        return View(model);
  }

 [HttpPost]
 public ActionResult GeneratePackage(ITViewModel model)
    {
    _Repository.SavePackage(model);

    //Generate Zip file Package
    //Get file template  in archiveStream
            Response.Clear();
            Response.ContentType = "application/zip";
            Response.AppendHeader("content-disposition", "attachment; filename="testzipPackage");
            Response.CacheControl = "Private";
            Response.Cache.SetExpires(DateTime.Now.AddMinutes(3));
            Response.Buffer = true;
            var writeBuffer = new byte[4096];

           var count = archiveStream.Read(writeBuffer, 0, writeBuffer.Length);
            while (count > 0)
            {
                Response.OutputStream.Write(writeBuffer, 0, count);
                count = archiveStream.Read(writeBuffer, 0, writeBuffer.Length);

           }
    model.Packages = _Repository.GetDeployedPackages(model.id) //get the correct package list with the one tht we just saved on this ActionResult

    return View("Index",model);
    }

    //Index
    @model  ITViewModel
    @using (Html.BeginForm("GeneratePackage", "Integration", FormMethod.Post)
{
    //some input form 
}

<table>
 @foreach (var package in Model.Packages)
            {
<tr>
<td>
        @package.Name
</td>
</tr>
}
</table>

I am able to download the zip file correctly. In the debugger I also see the Package list with the newly added element. But the View on Post is not getting refreshed. I mean the table on the Index doesn’t refresh with the new model element. Even the document.ready is not getting called once return View("Index",model) is fired.

 I have tried ModelState.Clear(). It didn't work.

Upvotes: 0

Views: 541

Answers (1)

Federico Dipuma
Federico Dipuma

Reputation: 18265

You cannot return two different responses from a single HTTP request.

Here you are writing the response:

Response.OutputStream.Write(writeBuffer, 0, count);

Anything you do after that is not handled by the server or the client.

Your web browser is downloading the file and than just stays on the same page. That's absolutely normal.

If you want to refresh the page you may need to do it using JavaScript client-side.

Here it is a small example using jQuery assuming myForm as your form id:

$('#myForm').submit(function() {
    setTimeout(function () {
        window.location.reload();
    }, 1000); // use a timeout as big as you need
});

You may also need to add target="_blank" to your form tag.

Upvotes: 1

Related Questions