我试图将HomeController中的查询参数值传递给另一个名为PasscodeVerificationController的控制器,该控制器呈现一个新视图。这个视图有一个名为verify的按钮,它从用户那里获取一个密码并将调用发送回PasscodeVerificationController中的动作,在整个过程中我需要传递查询参数,但是当调用action方法时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; }
}
您需要为希望在帖子上返回的歌手模型的所有成员隐藏。
@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
,该对象在发布表单时不会填充/绑定模型。