【问题标题】:Model returned from View does not have the value set in the view when call comes back to controller当调用返回到控制器时,从视图返回的模型没有在视图中设置的值
【发布时间】:2019-04-03 07:30:43
【问题描述】:

我正在尝试将查询参数值从 HomeController 传递到另一个名为 PasscodeVerificationController 的控制器,该控制器呈现一个新视图。此视图有一个名为 verify 的按钮,它从用户那里获取密码并在 PasscodeVerificationController 中发送回调到操作,在整个过程中我需要传递查询参数,但是当调用到操作方法时,Razor 视图中设置的值会丢失

以下是查看代码

@model Test.Models.PasscodeVerificationModel

@using (Html.BeginForm("verify", "PasscodeVerification", FormMethod.Post))
{
    <h2>Enter your passcode here</h2>
    Test.Models.SignerModel signer = ViewBag.Signer;
    @Html.TextBoxFor(model => model.Passcode)
    @Html.ValidationMessageFor(model => model.Passcode)
    @Html.HiddenFor(x => Model.signerModel)
    <input type="submit" value="Verify" />
}

以下是控制器代码

    public class PasscodeVerificationController : Controller
    {
        [ActionName("passcode")]
        public ActionResult Index(SignerModel signer)
        {

           /*Here signer has the value and its being passed to view and I can 
           confirm in the view this value exists */
               ViewBag.Signer = signer;
               return View("~/Views/Passcode/Index.cshtml", new PasscodeVerificationModel { signerModel = signer});
        }

        [HttpPost()]
        [ActionName("verify")]
        public ActionResult Verify(PasscodeVerificationModel tokenVerificationModel)
        {
            /*Signer model value is always null :( :( */
            var signerModel = tokenVerificationModel.signerModel;

            if (tokenVerificationModel.Passcode == "1234")
            {
                if (signerModel == null || string.IsNullOrWhiteSpace(signerModel.ReturnUrl))
                {
                    return Content("No return url");
                }


                return Redirect(WebUtility.UrlDecode(signerModel.ReturnUrl));
            }
            else
            {
                return Content("Verification failed");
            }
         }
      }


    public class PasscodeVerificationModel
    {
        [Required]
        [StringLength(8, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 4)]
        public string Passcode { get; set; }

        public SignerModel signerModel { get; set; }
    }

【问题讨论】:

  • 你需要为歌手模型的所有成员做一个隐藏。将整个对象传递给隐藏的不会工作
  • @Nkosi 谢谢你的帮助,你想添加这个作为答案吗?我会将其标记为已接受

标签: asp.net-mvc razor


【解决方案1】:

您需要对希望在帖子中返回的歌手模型的所有成员进行隐藏。

@Html.HiddenFor(model => model.signerModel.Property1)
@Html.HiddenFor(model => model.signerModel.Property2)
@Html.HiddenFor(model => model.signerModel.Property3)
<!-- ... -->
@Html.HiddenFor(model => model.signerModel.PropertyN)

将整个对象传递给隐藏的 html 帮助程序将不起作用,因为它只会返回对象的 ToString,当表单发布时不会填充/绑定模型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-13
    • 2020-11-06
    • 2012-11-07
    相关资源
    最近更新 更多