剃刀视图上的模型未在表单提交上更新

时间:2017-05-17 17:07:07

标签: c# asp.net asp.net-mvc httpresponse

  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>

我可以正确下载zip文件。在调试器中,我还看到包含新添加元素的包列表。但是Post on Post没有得到更新。我的意思是索引上的表不会刷新新的模型元素。即使是document.ready也没有被调用过一次 触发视图(&#34;索引&#34;,模型)被触发。

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

1 个答案:

答案 0 :(得分:1)

您无法从单个HTTP请求中返回两个不同的响应。

您正在撰写回复:

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

之后您执行的任何操作都不会由服务器或客户端处理。

您的网络浏览器正在下载文件,而不是只停留在同一页面上。这绝对是正常的。

如果您想刷新页面,可能需要使用JavaScript客户端来完成。

这是一个使用jQuery的小例子,假设myForm为表单ID:

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

您可能还需要在表单标记中添加target="_blank"