[英]Child actions are not allowed to perform redirect actions MVC4
我对MVC还是很陌生。 这使我整日发疯,我一直在阅读,似乎我的代码结构中可能存在一些基本错误。 但是我正在努力查看它们的确切含义。 据我所知,我什至不使用儿童动作?
在返回的RedirectToAction行上引发了错误。
我有一个以表格形式显示的注册表。 这种模式可以在许多页面上看到-因此我创建了一个返回部分视图的动作。
[AllowAnonymous]
public ActionResult RegisterPartial()
{
return PartialView(new RegisterModel());
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult RegisterPartial(RegisterModel model)
{
if (ModelState.IsValid)
{
//do stuff
return RedirectToAction("Data", "Settings", new { id = model.UserName });
}
// If we got this far, something failed, show form again
return PartialView(model);
}
目前,这是从我的主页上调用的-但最终会在许多页面上调用。
<div class="modal fade" id="signUpModal">
@Html.Action("RegisterPartial", "Account")
</div>
<a href="#" style="color:#fff;" class=" btn btn-lg btn-primary" data-toggle="modal" data-target="#signUpModal">SignUp</a>
这是局部视图本身
@model Prog.Models.RegisterModel
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title">Signup</h4>
</div>
@using (Html.BeginForm())
{
<fieldset>
<div class="modal-body">
<p class="message-info">
</p>
@Html.ValidationSummary()
@Html.AntiForgeryToken()
<ol>
<li>
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName, new { @maxlength = "13" })
@Html.ValidationMessageFor(m => m.UserName)
</li>
<li>
@Html.LabelFor(m => m.email)
@Html.TextBoxFor(m => m.email)
@Html.ValidationMessageFor(m => m.email)
</li>
<li>
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password)
</li>
<li>
@Html.LabelFor(m => m.ConfirmPassword)
@Html.PasswordFor(m => m.ConfirmPassword)
</li>
@Html.ValidationMessageFor(m => m.ConfirmPassword)
</ol>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Post</button>
</div>
</fieldset>
}
</div></div>
非常感激任何的帮助! 提前致谢 :)
原来是因为我没有正确填写html begin form语句。
@using (Html.BeginForm("RegisterPartial", "Account", FormMethod.Post , new { @class = "form-horizontal" }))
这现在有效。
问题是如果modelstate无效,您的POST操作将返回PartialView。 因此,部分视图将显示为整个页面而不是模型。 因此,您可以使用Ajax表单。 有可用于MVC的Ajax帮助器。
在页面中包含以下脚本。
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
您的观点将是
@using (Ajax.BeginForm("RegisterPartial", "Account", new AjaxOptions() {
OnSuccess = "successCallback"})
{
}
<script>
function successCallback(response)
{
var username='@Model.UserName';
if(response)
{
windows.href.location='/Settings/Data/'+username;
}
}
</script>
您的动作将是
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public JsonResultRegisterPartial(RegisterModel model)
{
if (ModelState.IsValid)
{
//do stuff
return Json(new {Success=true });
}
return Json(new {Success=false});
}
这可能会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.