当调用返回到控制器时,从View返回的模型未在视图中设置值

时间:2019-04-02 00:30:30

标签: asp.net-mvc razor

我试图将查询参数值从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; }
    }

1 个答案:

答案 0 :(得分:2)

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

@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,而该对象将在表单发布时填充/绑定模型。