将对象传递回HttpPost中的视图 [英] Passing Object Back to View in HttpPost

查看:55
本文介绍了将对象传递回HttpPost中的视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将简化它,这是我得到的代码.

I'll make it simple, here's the code I've got.

  public ActionResult DeleteNonCIStaffUser(int id)
  {
    return View(_contractsControlRepository.FetchNonCIStaffUserByID(id));
  }

  [HttpPost]
  public ActionResult DeleteNonCIStaffUser(ContractUser contractUser)
  {
    try
    {
      _contractsControlRepository.DeleteNonCIStaffUser(contractUser.User_Key);
      return RedirectToAction("NonCIStaffUsers"); // never reaches this as an exception is thrown!
    }
    catch
    {
      ViewData["ExceptionMessage"] = "Exception caught!";
      return View(contractUser); // I'm expecting this statement to return the ContractUser object instantiated with the same data as the GET action.
    }
  }

HttpPost 包含 ContractUser 对象.回发后,我一无所有,contractUser对象不再存在,我觉得这很奇怪. FetchNonCIStaffByUser(int)带回ContractUser对象(有效).删除页面显示了来自该对象的信息,所以我知道初始输入有效,只是发生错误时的回发, ContractUser 对象中不会显示任何信息.

The HttpPost contains the ContractUser object. Upon the postback I am left with nothing, the contractUser object no longer exists, which I find rather odd. FetchNonCIStaffByUser(int) brings back a ContractUser object (which works). The delete page shows information from this object, so I know the initial entry works, it's just the postback if there's an error, no information is displayed from the ContractUser object.

有什么想法为什么会这样?我希望 contractUser 对象将返回到视图中.

Any ideas why this is happening? I'd have expected the contractUser object to be returned to the view.

已修复

 <%= Html.Hidden("FullName", Model.FullName) %>
 <%= Html.Hidden("User_Key", Model.User_Key) %>

这两个字段实际上都没有放在页面的表单元素中,因此没有回发任何内容.很高兴知道.

Neither fields were actually being put in form elements in the page so nothing was being posted back. Good to know.

推荐答案

调用 DeleteNonCIStaffUser 操作时,将从请求中填充 contractUser 对象(前提是您使用默认的模型绑定程序),因此属性将自动从请求中找到的信息进行绑定.这意味着在调用删除操作时,您需要传递所有 contractUser 的值(您可以将它们存储在页面的隐藏字段中).

When the DeleteNonCIStaffUser action is invoked, the contractUser object is populated from the request (provided you use the default model binder), so properties will be automatically bound from information found in the request. This means that you will need to pass all the values of the contractUser when invoking the delete action (you could store them in hidden fields in the page).

另一种选择是将ID传递给删除操作,使用FetchNonCIStaffUserByID填充模型,然后删除它,这当然会进行2次db调用.

Another option would be to pass just the ID to the delete action use FetchNonCIStaffUserByID to populate the model then delete it which of course would make 2 db calls.

这篇关于将对象传递回HttpPost中的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆