我试图将查询参数值从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; }
}
答案 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
,而该对象将在表单发布时填充/绑定模型。